Hi all,
Today we'll see how to modify the object returned by mongoose query.
Though MongoDB has rich library of query commands, the most common command used is "find()".
When using Mongoose to find documents, objects returned by find() command are mongoose document & not plain javascript objects. Thus they have some functionality available with it, as the Mongoose document.
The drawback of this feature is, you can't set any additional property to the document for further processing or for response.
To make this happen, Mongoose has provided with "lean()" method. The lean() method converts mongoose document to plain javascript object.
Note that this object will not have Mongoose methods associated with it. To refer to methods available with mongoose document follow this link.
Consider following example for illustration:
User schema:
User.js
{
name: String,
email: {
type: String,
unique: true
},
dob: Date
}
Now suppose you want to calculate age based on the dob & send this as a response, you can perform following query:
User.findOne({"email": <user_email>}).lean().exec(function (err, user) {
if (user) {
var curDate = new Date();
var age = curDate.getFullYear() - user.dob.getFullYear();
user.age = age; // added extra field
callback(null, user);
} else {
callback(err, null);
}
Enjoy!
Today we'll see how to modify the object returned by mongoose query.
Though MongoDB has rich library of query commands, the most common command used is "find()".
When using Mongoose to find documents, objects returned by find() command are mongoose document & not plain javascript objects. Thus they have some functionality available with it, as the Mongoose document.
The drawback of this feature is, you can't set any additional property to the document for further processing or for response.
To make this happen, Mongoose has provided with "lean()" method. The lean() method converts mongoose document to plain javascript object.
Note that this object will not have Mongoose methods associated with it. To refer to methods available with mongoose document follow this link.
Consider following example for illustration:
User schema:
User.js
{
name: String,
email: {
type: String,
unique: true
},
dob: Date
}
Now suppose you want to calculate age based on the dob & send this as a response, you can perform following query:
User.findOne({"email": <user_email>}).lean().exec(function (err, user) {
if (user) {
var curDate = new Date();
var age = curDate.getFullYear() - user.dob.getFullYear();
user.age = age; // added extra field
callback(null, user);
} else {
callback(err, null);
}
Enjoy!
Comments
Post a Comment