1

user (mongodb document)

{
  "_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": "[email protected]",
  "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) { ....

I want notidata to be sorted by notidate. Using $postion: 0 did not work. Nor did $sort: notidate: -1

* failed $position attempt*

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) {....

failed $sort attempt

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) {....

1 Answer 1

1

You have to use $sort with $each operator and then you just specify the name of nested field (not entire path like in your example), try:

User.findOneAndUpdate({ _id: user._id }, { 
    $push: {
        "notification.notidata": {
            "$each": [ { data: { para: "Your Ad " + "'" + thisad.heading + "'" + " has been successfully submitted." } } ],
            "$sort": {"notidate": -1}
        }
    }
}, {new: true})
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot! It worked. However, I wish to understand since every time this User.findOneAndUpdate will get executed in my app, it will have 1 entry of notidata.para to insert. Then why something like $eachneeds to be put in $push? Isn't $each for inserting more than one data (like an array of data)?
I know it might be confusing, it's even mentioned in the documentation that you should pass empty array if you only want to sort elements. That's by design
Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.