How to Save Data in MongoDB Database using Nodejs

Advertisement

Since we can now connect to the database, lets proceed to saving data in the database.

First, add the database name you intend to use to your URL. If your current URL is:

const  uri = "mongodb+srv://databaseadmin:<databasepassword>@cluster0.p198l.mongodb.net/?retryWrites=true&w=majority"

And ‘yob-2021’ is the name of the database, then your URL should be:

const  uri = "mongodb+srv://databaseadmin:<databasepassword>@cluster0.p198l.mongodb.net/yob-2021?retryWrites=true&w=majority"

To view and save data in the database, we need to define a Schema and create a model for it.

First create the Schema.

var nameSchema = new mongoose.Schema({
 firstName: String,
 lastName: String
});

The schema describes the kind of data you will be storing. For purposes of this tutorial, I will keep it simple.

Then create a model for the collection you will be using.

var UserModel = mongoose.model("users", nameSchema);

Where users is the collection name. You can find your current available databases and collections under each database by clicking the browse collections button at MongoDB Atlas.

[image]

You can now proceed to Read the Data stored in your database.

// Read MongoDB data
app.get("/users", async (request, response) => {
  const users = await UserModel.find({});
  try {
    response.send(users);
  } catch (error) {
    response.status(500).send(error);
  }
})

Visit, http://localhost:3000/users

You should see any data that have been saved on you collection.

To save data to you database, you can setup a simple function for testing purposes.

function postData(){
  const newuser = new UserModel({ firstName: "Company", lastName: "Highway" });
  newuser.save()
  .then(item => {
    console.log("item saved to database");
  })
  .catch(err => {
    console.log("unable to save to database");
  });
}

They, you can call the function within your app.get("/users", async (request, response) => {} function.

Visit, ```http://localhost:3000/users``` again.

You should see a new entry on the database. Since you are sure this is working, you can go ahead and setup Express post endpoint and Body parser to handle data from a form.

author's bio photo

Hi there! I am Avic Ndugu.

I have published 100+ blog posts on HTML, CSS, Javascript, React and other related topics. When I am not writing, I enjoy reading, hiking and listening to podcasts.