0

I am trying to get specific object value from items array. I am updating array by pushing new items into items array and then I want to get last updated item from an array. I have _id of the item that is last updated and using this query but it's returning complete record with all items.

 let repData = Items.findOne({'_id': rid, 'items._id': newRepId },{ "items.$": 1 });

 {
"errorCode": false,
"data": {
    "_id": "NhNpaN8EHn6uJXfg5",
    "cText": "Let me know you views",
    "aId": "YxEjFqsE3czZZJvgP",
    "cId": "EwDS5iYSEuGThHE38",
    "datePosted": "2019-07-11T07:13:59.177Z",
    "items": [
        {
            "reText": "pppppp sssssssss",
            "reOwn": "FK7KQ7eMs7QvX5uHh",
            "datePosted": "2019-07-11T07:19:17.722Z",
            "_id": "b87e532807ce37ff83d37a09"
        },
        {
            "reText": "bbbbbb vvvvvvvv",
            "reOwn": "FK7KQ7eMs7QvX5uHh",
            "datePosted": "2019-07-11T07:22:36.089Z",
            "_id": "28d2bf66a517bfcfaa0fabca"
        },
        {
            "reText": "mmmmmnnnnnn bbbbbbvvvvv",
            "reOwn": "FK7KQ7eMs7QvX5uHh",
            "datePosted": "2019-07-11T07:23:20.587Z",
            "_id": "85f52e3e3a8ae6d18e98dbb2"
        },


}
 }
1

1 Answer 1

0

The Mongo search will always get you the complete record, you can restrict the elements that you fetch, but you can't filter the items array, you will have to do that afterwards, something like this:

  const lastItem = repData.items
    .sort((a, b) => new Date(a.datePosted)-new Date(b.datePosted))
    .pop()
  console.log(lastItem)

Basically it sorts the array by date (perhaps not necessary), and then pops the last element into lastItem

Sign up to request clarification or add additional context in comments.

1 Comment

I have sorted it out by using forEach function and then matching id

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.