Step 12
Let's extract the Mongoose connection logic into its own module so we can reuse it!
Create a file db.js
inside the server/data
folder.
const mongoose = require("mongoose");
// TODO replace <password> with the password for quicknote-admin
const URI = `mongodb+srv://quicknote-admin:<password>@quicknote.ydsfc.mongodb.net/quickNoteDB?retryWrites=true&w=majority`;
async function connect() {
try {
await mongoose.connect(URI);
console.log("Connected to MongoDB!");
} catch (err) {
console.log(err);
}
}
module.exports = { connect };
Let's update the scripts/sampleNotes.js
file:
const faker = require("faker");
const db = require("../server/data/db");
const NoteDao = require("../server/data/NoteDao");
async function createSampleNotes() {
try {
await db.connect();
const notes = new NoteDao();
const note = await notes.create({
title: faker.lorem.sentence(),
text: faker.lorem.paragraph(),
});
console.log(note);
} catch (err) {
console.log(err);
}
}
createSampleNotes();
You can run this file a few times to create several sample notes!
Let's refactor the server/index.js
file as well:
- const faker = require("faker");
+ const db = require("./data/db");
- const NUM_SAMPLES = 3;
const notes = new NoteDao();
- for (let i = 0; i < NUM_SAMPLES; i++) {
- notes.create({
- title: faker.lorem.sentence(),
- text: faker.lorem.paragraph(),
- });
- }
+ db.connect(); // no need to await for it due to Mongoose buffering!
Save the changes and run the server:
npm run dev
Try the server in Postman and make sure everything works!