Wasiq Muhammad Wasiq Muhammad - 4 months ago 7
Node.js Question

Add to Collection if not found

I have an

embedded document
in my collection name as
likes
:

{
"_id" : ObjectId("57a31e18fa0299542ab8dd80"),
"created" : ISODate("2016-08-04T10:51:04.971Z"),
"likes" : [
{
"user" : ObjectId("1"),
"date" : 123
},
{
"user" : ObjectId("2"),
"date" : 456
}
],
"comments" : [],
"tag" : []
}


A
User
can like only one time. So there must be only one entry per
User
.

The problem is: It looks for
date
too in the object list, though I just want to search the
user
and add
current date
if entry not found. Because
date
differs every time and I get duplicated entries for same
user
.

Here is my
mongoose
query:

var likeObj = {
"user": "1", //user id
"date": Utils.getUnixTimeStamp() //date
};

post.update({_id: postId}, {$addToSet: {"likes": likeObj}} ,function(err,doc){
//success
});

Answer

You can add the user to the query:

 post.update({_id: postId, 
                 likes: {$not: {$elemMatch: {user: likeObj.user}}}},
                         {$addToSet: {"likes": likeObj}} ,function(err,doc){
       
    });