0

i want to search into an embed document in mongodb and return only what i'm looking for. Here's the document:

"_id" : "yH8HmCPz6H6E8Hinq",
"between" : [
    "4bgdLrztpqgwAkZP4",
    "9jZhXHjAkoY7mmX7B"
],
"messages" : [
    {
        "content" : "fdsqf",
        "user" : "4bgdLrztpqgwAkZP4",
        "created_at" : ISODate("2016-11-17T23:13:59.659Z"),
        "isSeen" : false,
        "sender" : "John doe",
        "receiver" : "Elen doe"
    },
    {
        "content" : "test",
        "user" : "9jZhXHjAkoY7mmX7B",
        "created_at" : ISODate("2016-11-20T11:42:42.893Z"),
        "isSeen" : false,
        "sender" : "Elen doe",
        "receiver" : "John doe"
    }
]

All what i want to have is "messages.isSeen" equals to false and receiver isn't Meteor.user().username.

And finally how to update that field to become true.

Hope someone can help ! Thanks in advance !

  • I'm not entirely certain but does minimongo support $match and $project? – blueren Nov 20 '16 at 17:14
  • You can check out [this](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) answer – blueren Nov 20 '16 at 17:21
  • The probleme is i need to find the conversation by id then fetch for messages whom receiver is "John doe" for instance and then update the field. i've tried everything but nothing worked !! – Issam Elyazidi Nov 20 '16 at 17:49

2 Answers2

0

You need something like:

Chat.update({
  'messages.isSeen': false,          // isSeen is false
  'messages.receiver': {             // Receiver is
     $ne: Meteor.user().username     // not equal to Meteor.user().username
  }
}, {
  'messages.$isSeen': true           // Set isSeen to true
});
tbking
  • 8,796
  • 2
  • 20
  • 33
  • i need to find the conversation with the id first ! because it's a unique conversation between x and y ! and the find who receive the message, and then update the field isSeen. – Issam Elyazidi Nov 20 '16 at 17:50
  • I think just adding an `_id` field in the query will do the job. Don't you think? – tbking Nov 20 '16 at 18:54
  • Not working, i've tried everything ! it's really not working ! that's why i'm here ! kind of weird, because when i add anything else than the _id, it returns an empty object ! – Issam Elyazidi Nov 20 '16 at 19:30
0

You need to include the _id in the query and $set in the update.

let id = "yH8HmCPz6H6E8Hinq";
let username = Meteor.user().username;
let query = { _id: id, messages: { $elemMatch: { isSeen: false, receiver: { $ne: username }}}};
Chat.update(query,{ $set: { "messages.$.isSeen": true }});
Michel Floyd
  • 18,793
  • 4
  • 24
  • 39