用户(mongodb文档)
{
"_id": "5bccfb7515bc6d0c6872ed91",
"notification": {
"notidata": [
{
"data": {
"para": "Your Ad '1' has been successfully submitted."
},
"notistatus": false,
"_id": "5be35d89113aec40c4ca7517",
"notidate": "2018-11-07T21:47:53.803Z"
},
{
"data": {
"para": "Your Ad '2' has been successfully submitted."
},
"notistatus": false,
"_id": "5be35d92113aec40c4ca7519",
"notidate": "2018-11-07T21:48:02.729Z"
}
],
"counter": 4
},
"ads": [],
"username": "mesam",
"email": "mesam@hotmal.com",
"password": "0",
"country": "AZE",
"createdOn": "2018-10-21T22:19:33.377Z",
"__v": 0
}
route.js
User.findOneAndUpdate({ _id: user._id }, { $push: { "notification.notidata": { "data.para": "Your Ad " + "'" + thisad.heading + "'" + " has been successfully submitted."} } }, { new: true }, function (err, df) { ....
我希望notidata
按notidate
排序。使用$postion: 0
无效。 $sort: notidate: -1
* $排名尝试失败*
User.findOneAndUpdate({ _id: user._id }, { $push: { "notification.notidata": { "data.para": "Your Ad " + "'" + thisad.heading + "'" + " has been successfully submitted.", "$position": 0} } }, { new: true }, function (err, df) {....
$ sort尝试失败
User.findOneAndUpdate({ _id: user._id }, { $push: { "notification.notidata": { "data.para": "Your Ad " + "'" + thisad.heading + "'" + " has been successfully submitted.", "$sort": {"notification.notidata.notidate": -1}} } }, { new: true }, function (err, df) {....
答案 0 :(得分:1)
您必须将$sort与$each
运算符配合使用,然后仅指定嵌套字段的名称(而不是示例中的完整路径),请尝试:
User.findOneAndUpdate({ _id: user._id }, {
$push: {
"notification.notidata": {
"$each": [ { data: { para: "Your Ad " + "'" + thisad.heading + "'" + " has been successfully submitted." } } ],
"$sort": {"notidate": -1}
}
}
}, {new: true})