Push items into mongo array via mongoose

前端 未结 8 1394
小鲜肉
小鲜肉 2020-11-22 03:22

I\'ve scoured SO a good bit looking for the answer but I\'m sure that I\'m lost for the right words to describe what I\'m after.

Basically I have a mongodb collection

8条回答
  •  别那么骄傲
    2020-11-22 04:04

    The $push operator appends a specified value to an array.

    { $push: { : , ... } }
    

    $push adds the array field with the value as its element.

    Above answer fulfils all the requirements, but I got it working by doing the following

    var objFriends = { fname:"fname",lname:"lname",surname:"surname" };
    Friend.findOneAndUpdate(
       { _id: req.body.id }, 
       { $push: { friends: objFriends  } },
      function (error, success) {
            if (error) {
                console.log(error);
            } else {
                console.log(success);
            }
        });
    )
    

提交回复
热议问题