Populating the DB

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 277:- Populating the DB

here is an example of how to populate a MongoDB database using Mongoose:

javascriptCopy code

const mongoose = require('mongoose'); const { Contact } = require('./models'); mongoose.connect('mongodb://localhost:27017/contactList', {  useNewUrlParser: true,  useUnifiedTopology: true,  useCreateIndex: true, }); const contacts = [  { name: 'John Doe', phone: '555-1234', email: '[email protected]' },  { name: 'Jane Smith', phone: '555-5678', email: '[email protected]' },  { name: 'Bob Johnson', phone: '555-9012', email: '[email protected]' }, ]; async function seedDatabase() {  try {    await Contact.insertMany(contacts);    console.log('Database seeded successfully!');    mongoose.connection.close();  } catch (error) {    console.error(error);  } } seedDatabase();

In this example, we first require Mongoose and our Contact model. Then, we connect to the MongoDB server running locally on port 27017 and specify some options for the connection.

Next, we define an array of contacts that we want to add to the database. We then create an async function called seedDatabase that uses insertMany to insert the contacts into the database. If the insertion is successful, we log a message to the console and close the database connection. If there is an error, we log the error to the console.

Finally, we call the seedDatabase function to populate the database.

31. My First Express App - Intro To Databases

2 Comments

@niteshguptav63
niteshguptav63 Nov 17, 2024 at 1:39 PM

I am not able to access videos from second class and further. I have already completed first class

@niteshguptav63
niteshguptav63 Nov 16, 2024 at 10:56 AM

When will I get my course?

@admin79
admin79 Nov 17, 2024 at 1:29 PM

Now, Your query was resolved.

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support