0

Im mapping over an array of objects and adding a value for "latestMessage"

The latest() function searches for the message and returns and object. But the reult of the map does not contain the new property. If I remove the latest function and just put a string though it works.

function latest(userId) {
  Chat.findOne({ $or: [{ to: userId }, { from: userId }] }, {}, { sort: { createdAt: -1 } }, function (err, msg) {

    return msg

  })
}

Does not work:

let array = users.map(v => ({ ...v._doc, latestMessage: latest(v._id) }))

Works:

let array = users.map(v => ({ ...v._doc, latestMessage: {test: 'test'} }))

1 Answers1

0

Since Chat.fineOne is running a callback function, you have to do your logic in that function. I'm not sure how they rest of your application is setup, but you might be able to create the object and pass it to your query. The query can update the object when the callback happens. Note, this will be after the map has already been created since it's async.

let array = users.map(v => {
  let value = { ...v._doc, latestMessage: "" };
  setLatest(value);
  return value;
});

function setLatest(value) {
  Chat.findOne({ $or: [{ to: value._id }, { from: value._id }] }, {}, { sort: { createdAt: -1 } }, function (err, msg) {
    value.latestMessage = msg;
  })
}
Todd Skelton
  • 6,839
  • 3
  • 36
  • 48