node.js - mongoose: Sorting by id -
mongo db reorders documents when ever document updated. dint want happen found using order _id homecoming documents in consistent order. not able sort. below find query finds posts created particular user , trying sort _id. code:
app.get('/posts/:user_id',function(req,res){ posts.find({ 'creator.user_id':req.params.user_id },[],{ sort: { '_id': -1 } },function(err,userpost){ if(err) res.send(err); res.json(userpost); }) });
the sec parameter fields select. need add together options 3rd parameter:
posts.find({'creator.user_id': req.params.user_id}, null, {sort: {'_id': -1}}, function(err,userpost) { if(err) res.send(err); res.json(userpost); });
alternatively can utilize sort()
function:
posts.find({'creator.user_id': req.params.user_id}).sort({'_id': -1}).exec(function(err,userpost) { if(err) res.send(err); res.json(userpost); });
you can find more examples in documentation.
node.js mongodb mongoose
No comments:
Post a Comment