I have problem trying to do a sort by date of updated_at "post" (subdocument), with the code below i see the posts in order of creation. I need sort by date of updated.
var postSchema = new mongoose.Schema({
post: String,
created_at: { type: Date, default: Date.now },
updated_at: Date
});
var UserSchema = new mongoose.Schema({
username: String,
password: String,
posts: [postSchema]
});
app.get("/val",isLoggedIn, function(req, res){
var aca = req.user._id;
User.findById({_id: aca},function(err, myposts){
if(err){
console.log(err);
} else {
res.render("index", {dataposts:myposts});
}
});
});
I would suggest following, using $order_by
User.findById({ $query : {_id: aca},$orderby: {updated_date: -1} })
In latest versions of mongoose this should work,
User.findById({_id: aca}).sort({updated_at:-1}).exec(function(err, myposts) {... });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.