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"
        },


}
 }
user3714488
  • 103
  • 1
  • 3
  • 15
  • Similar question: https://stackoverflow.com/questions/28680295/mongodb-query-on-the-last-element-of-an-array – Jankapunkt Jul 11 '19 at 09:44

1 Answers1

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

Mikkel
  • 7,693
  • 3
  • 17
  • 31