Use lean in mongoose with callback - mongodb

I am trying to use lean in my mongoDB query but the problem I am facing is that I don't use .exec() method. I use callback implementation like below
model.find({user_id: mobile_no }, {'_id':0, 'type':1}, {sort: {dateTime: -1}, skip: page*page_size, limit: page_size + 1}, function(err, docs) {
if (err) {
} else {
}
});
but in most documentation,everyone uses lean with .exec() like below
.lean().exec()
Can anyone please tell me how can I use lean using my callback implementation or I would have to use .exec() implementation in order to use it.

You can use both .exec() and callbacks:
model.find(...).lean().exec(function(err, docs) {
...
});
See also the documentation, where one of the examples does the same.

model.find({user_id: mobile_no }, {'_id':0, 'type':1}, {sort: {dateTime: -1}, skip: page*page_size, limit: page_size + 1}, function(err, docs) {
if (err) {
} else {
}
}).lean();
You have to write .lean() at the end of the query :3

Related

MongoDB $sort using aggregate is really slow

I am creating a new field during aggregation in order to sort result by relevancy. Unfortunately the $sort method just slow down my request execution. Can you explain me how to make it faster ?
Here my code :
MyClass.aggregate([
{"$match": query}
,{
"$project" : Object.assign({
//
// Build relevancy score
//
"relevancyScore": {blablabla...}
}, otherFields)
}
,{"$sort":{"relevancyScore":-1}} // This line slow down the request
,{"$skip": currentPage * pageSize}
,{"$limit": pageSize}
])
.exec(function (err, res) {
if (err) return console.log("error", err);
resolve(res);
});
If I $sort by '_id' it is really fast because _id field is indexed. Unfortunately my relevancyScore field is created in flight...
Thank you ! :D

Return only created subdocument mongoose

I need to push a new document into an array and use his _id.
Right now im using findOneAndUpdate, i know i can use { new: true } but i only need the created document and not the parent document.
this is my code so far
User.findOneAndUpdate(
{
'posts._id': req.params.id
},
{
$push: {
'posts.$.comments': {
from: {
_id: req.user._id,
username: req.user.username,
},
body: req.body.commentBody
}
}
},
err => {
if (err) console.log(err)
// Do something with ObjectId
}
);
Thanks in advance.
findOneAndUpdate callback gives you the updated document.
You have the Post's _id. You can use that to find the post to which you are adding the comment to. As you are pushing the comment, it will be the last element in the post array.
var mypost = doc.posts.find(function(post){
return post._id.toString()==req.params.id
});
console.log(mypost.comments[mypost.comments.length]._id)

Strong Loopback group_by aggregation

I have searched a lot to find a way for aggregation using loopback mongodb, unfortunately no perfect solution found. One of them is here
But can't implement this, any one to help me solve this problem, with any new solution, or describing above link.
Loopback doesn't provide a way to do an aggregation query, but you can find another solution in: https://github.com/strongloop/loopback/issues/890
//Using the datasource we are making a direct request to MongoDB instead of use the PersistedModel of Loopback
var bookCollection = Book.getDataSource().connector.collection(Book.modelName);
bookCollection.aggregate({
$group: {
_id: { category: "$category", author: "$author" },
total: { $sum: 1 }
}
}, function(err, groupByRecords) {
if(err) {
next(err);
} else {
next();
}
});

Mongodb in operator in find Query

I have a query as mentioned below.
var projstat = ['A' , 'B'];
Post.native(function(err, collection) {
if (err)
console.log(err);
collection.find({
'status': {
"$in": projstat
}
}, {multi: true}, function(err, result) {
console.log(result);
if (req.isSocket) {
return res.json(result);
}
});
});
Please correct me if i am wrong as it doesnot return any results. Please help.
You're not using the native find correctly; rather than using a callback as an argument (like Waterline does), you chain the call to toArray and use the callback as its argument:
collection.find({
'status': {
"$in": projstat
}
}).toArray(function(err, results) {...});
Docs for the native Mongo driver are here.
However, the more important point in this case is that you don't need native at all. You can use the regular Waterline find, which automatically does an in query when an attribute is set to an array:
Post.find({status: projstat}).exec(function(err, results) {...});

How to get string value inside a Mongodb document?

I have this document stored in mongodb document:
{
"_id":ObjectId("4eb7642ba899edcc31000001")
"hash":"abcd123"
"value":"some_text_here"
}
I am using NodeJS to access the database:
collection.findOne({'hash' : req.param('query') },
function(err, result){
console.log(res);
});
The result of this query is the whole document, however I need to get only the "value" text: "some_text_here"
How can this be done?
You can specify the fields that you are interested in (_id will always be returned, though):
collection.findOne({'hash': req.param('query') },
{fields: ['value'] },
callbackFunction );
You can do it such way:
collection.findOne({'hash' : req.param('query') },
function(err, result){
console.log(result.value);
});