Friday 21 April 2017

Adding an object to an array using mongoose if value not found, otherwise updating fields

I'm using mongoose to handle MongoDB.

I have the following document

Posts:Array
    0:Object
        _id:58f9b2c903110b2c543fb7d1
        postName:Test1
        postText:Test2
        postCount:0
        status:true

I would like to do a HTTP request to update or insert an object to this array based on postName.

for example, if I pass the following

{
    postName:Test1
    postText:Test3
    postCount:50
    status:false
}

Than postName matches and I would like it to just update postText, postCount and status. If postName does not matches any one of the objects in the array, I would like it to insert a new object.

This question maybe duplicate to old questions, I searched and I couldn't find the answer. I also tried to use $setOnInsert but couldn't get it working.



via Liron Toval

No comments:

Post a Comment