Reputation: 465
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.
Upvotes: 5
Views: 610
Reputation: 21
Yesterday I read @Aya Othman's answer several times and understood it only after reading the Mongoose documents a few times. So I thought maybe noobs like myself need a bit different explanation. As I understood, we know that Mongoose models have several functions for CRUD operations such as Model.find()
, Model.findById()
, Model.findByIdAndDelete()
, etc. For example, when User.findById(userId)
function is invoked without keyword await
it doesn't fetch the user from the database and return document but it returns a query. This query is an object. It has methods. Now if we want to fetch the user we can call exec()
method of the query.
const query = User.findById(userId)
// fetch only user's name and age
query.select("name age")
// execute query at a later time
// `await query.exec()` is equivalent to `await User.findById(userId)`
const user = await query.exec()
console.log(user instanceof mongoose.Document) // true
For further details I recommend reading about Queries and Documents.
Upvotes: 1
Reputation: 136
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)
})
Upvotes: 3