Read the documents using Mongoose

Rubleen Kaur
Last Updated: May 13, 2022

Introduction

Mongoose is a powerful Node.js Object Data Modeling(ODM) module that provides MongoDB functionality to your Express app. This blog will discuss how we can read documents from a collection and have the find() function.
 


In this article, we will briefly explain how we can read the documents using Mongoose. We use all of the methods directly on the model object to read documents. Mongoose represents a one-to-one mapping to documents similar to MongoDB. Each record in Mongoose is an instance of the Model Class.

Do you want to learn more? Let’s go!! 

 

Methods used for Reading the document

Mongoose provides us with three primary methods to read stuff from the database, which are- 

(.find(), .findOne() and .findById()). Mongoose also provides us with an advanced method to read the data, that is the .where() method. 

.find([query], callback])

Lets’s go through an example to understand how the above method is used to read information from the document. 

const Person = require("../models/person");
Person.find((err, people) => {
if (err) return res.status(500).send(err)
return res.status(200).send(people);
});
Person.find({name: "Coding Ninjas", age: 20}, (err, people) =>{ if (err) return res.status(100).send(err)
return res.status(300).send(people); });

 

In the example discussed, the .find() method is used to find all the database instances that match the query passed in the function. This method is used to return an array, even if the collection contains a sole value.

.findOne([query], [fieldsToReturn], [callback])

The findOne method is used to find the object from the database. When the query matches more than one row, the findOne method returns the first row content from the database. 

Ninja.findOne( 
// query 
{
class: "first"
name: "NinjaCoder"
age: 20
}, 
// Only return an object with the "name" and "course" fields. "_id",
// is included by default, so you'll need to remove it if you don't want it. 
{

name: true

course: true

}, 
// callback function 

(err,ninja) => 
if (err) 
    return res.status(200).send(err)
 return res.status(200).send(ninja) 
});

 

Using the findOne method, we can do the following functions:

  • If a query has not been provided in the method, the function returns the first value in the Database row.
  • If no fieldsToReturn is provided in the method, the function returns the entire object.
  • We can pass multiple strings using space in the category of fieldsToReturn instead of an entire object.

 

.findById(id, [fieldsToReturn], [callback])

The .findById method is used for finding a single object using the id passed in the method. 

//Common RESTful way to get the Id is from the URL params in req.params.
Ninja.findById(req.params.ninjaId, (err,ninja) => 

if (err) 
return res.status(100).send(err) 
return res.status(600).send(ninja) 
});

 

 

Documents vs. Models

So the model class and the document class are two distinct classes in Mongoose. The model class is the subclass of the document class. Every document is an instance of the model class. When we call the model constructor, a new document is created. Let’s use some coding to get familiar with these two concepts,

const MyModel = mongoose.model('Test'new Schema({ nameString }));
const doc = new MyModel();

doc instanceof MyModel; // true
doc instanceof mongoose.Model; // true
doc instanceof mongoose.Document; // true

 

Retrieving 

When we load documents using the MongoDB database, we use functions like findOne() to retrieve the Moongoose document back. Interesting, isn’t it?

Let’s see an example for the same,

 

const doc = await MyModel.findOne();

doc instanceof MyModel; // true
doc instanceof mongoose.Model; // true
doc instanceof mongoose.Document; // true

 

Updating the document using save()

The documents are tracked using Mongoose. We can easily modify the document using vanilla javascript, and Mongoose converts the document into MongoDB update operators.

doc.name = 'foo';

// Mongoose sends an `updateOne({ _id: doc._id }, { $set: { name: 'foo' } })`
// to MongoDB.
await doc.save();

 

The save() method is used to return a promise. 

doc.save().then(savedDoc => {
  savedDoc === doc// true
});

 

When the document with a corresponding id is not found, the Mongoose reports a DocumentNotFoundError. 

Updating the document using queries

When the save() method is not flexible enough, Mongoose allows you to create your own MongoDB updates with casting, middleware, and limited validation.

// Update all documents in the `mymodels` collection 
await MyModel.updateMany({}, { $set: { name: 'ninja' } });

Overwriting

There are two different ways to overwrite a document, which replaces all the keys in the document. One way to do this is by using the Document#overwrite() method followed by the save() method. 

const doc = await Person.findOne({ _id });

// Sets `name` and unsets all other properties.
doc.overwrite({ name: 'coding ninjas' });
await doc.save();

 

The second way to do overwriting is to use Model.replaceOne().

// Sets `name` and unsets all other properties
await Person.replaceOne({ _id }, { name: 'coding ninjas' });

 

Frequently Asked Questions

  1. What is the difference between Mongoose and MongoDB?
    AnsMongoDB is the native Node.js driver for communicating with a MongoDB instance, whereas Mongoose can be used as an Object modeling tool for MongoDB databases. Mongoose was developed on top of the MongoDB driver to provide programmers with a means to model their data.
     
  2. How can you read the documents in Mongoose?
    Ans: To read documents from a collection, we have the find() function. We use all of the methods directly on the model object to read documents.
     
  3. What is the difference between Documents and Models?
    Ans: In Mongoose, the document is an instance of the Model class. We can use the model constructor to create a new document. 

Key Takeaways

Hey everyone, so let’s brief out the article. Let’s discuss in brief whatever we have discussed here. 

  • We have explained how we can read the documents using Mongoose. We use all of the methods directly on the model object to read documents. Mongoose represents a one-to-one mapping to documents similar to MongoDB. Each document in Mongoose is an instance of the Model Class.
  • After discussing the basics of reading the documents using Mongoose, we have gone over each type of method used for reading the documents in Mongoose. 
  • The article then covers various concepts like Documents vs. Models, Retrieving, Updation of the document using the save() method, and Updation of the document using the queries. At last, we have covered the concept of Overwriting. 

 

Isn’t Web Development engaging? Building new websites and using amazing animations and different APIs, don’t be scared if you cannot grasp the hold of this vast development. We have the perfect web development course for you to make you stand out from your fellow developers. 

 

Happy Learning Ninjas!

 

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think