Search code examples
mongoose

Difference between Document and Query in mongoose?


According to the mongoose documentation:

Mongoose models provide several static helper functions for CRUD operations. Each of these functions returns a mongoose Query object.

Models are fancy constructors compiled from Schema definitions.

Mongoose documents represent a one-to-one mapping to documents as stored in MongoDB. Each document is an instance of its Model.

Now, all the static CRUD functions on the Model return a Query. However, in the documents section, under guides, it says "When you load documents from MongoDB using model functions like findOne(), you get a Mongoose document back.".

At one place Model.findOne() is returning a Query object and at a different section its returning a document...Can someone please help explain this.


Solution

  • Really a good question. Simply creating a query doesn't mean loading the document from the Model. When you use findOne() method you just create a query, it will return Query Object. When you execute this query to load the document from the model, in this case the return is a document Object. Hope the following example will clarify the idea, knowing that this is not the only way to execute the query.

    The first part is to create the query

        const query = myModel.findOne({ name })
        console.log(query.constructor.name) // Query
        console.log(query instanceof mongoose.Query) // True
        console.log(query instanceof mongoose.Document) // False
    

    The second part is to execute it

        query.then((document) => {
            console.log(document.constructor.name) // model
            console.log(document instanceof mongoose.Query) // False
            console.log(document instanceof mongoose.Document) // True
            response.json(document)
        }).catch((error) => {
            response.json(error)
        })