如何在Mongodb节点js中更新数组的多个元素

时间:2016-04-08 11:05:32

标签: arrays node.js mongodb

我需要通过complaints._id更新我的投诉数组对象元素这是我的mongo文档。

{ 
  "_id": "570785f0752eab040f347a70",
  "createdAt": "2016-04-08T10:20:32.606Z",
  "updatedAt": "2016-04-08T10:20:32.606Z",
  "bookingid": "5704bd7cbd881ba413274c06",
  "specialInstruction": "no special instruction",
  "complaints": [
    {
      "complaint": "head light is not working",
      "_id": "570785f0752eab040f347a72",
      "labour": 0,
      "partCost": 0,
      "part": [],
      "acceptance": false,
      "inspection": false,
      "color": "#CE002D",
      "status": "WAITING",
      "estimate": 0,
      "solution": "",
      "problems": ""
    },
    {
      "complaint": "clutch is not good condition",
      "_id": "570785f0752eab040f347a71",
      "labour": 0,
      "partCost": 0,
      "part": [],
      "acceptance": false,
      "inspection": false,
      "color": "#CE002D",
      "status": "WAITING",
      "estimate": 0,
      "solution": "",
      "problems": ""
    }
  ],
  "__v": 0
}

我正在尝试这种方法,但它无法正常工作

funcs.updatecomplaints=function(request, reply){
    var id=request.params.complaintid;
    console.log('TESTING'+id);

    CPS.findByIdAndUpdate(request.params.documentid, {complaints:{ 
        $set: { status: "WAITING", color : "#CE002D",$where: _id=id}}},
        {upsert:true}, function (err, booking) {
            Booking.findById(id, function(err, newbooking){
                if(err){
                    console.log('Errorrrr Occured'+JSON.stringify(err));
                    return  reply(JSON.stringify(err)).code(500);
            }else{
                console.log('All Booking are---->>'+booking);
                return reply(newbooking).code(200);
            }
            });

        });

1 个答案:

答案 0 :(得分:0)

对于您的问题,我建议使用简单的update api而不是findByIdAndUpdate,因为您不会按ID搜索,但会按complaints._id进行搜索,然后使用{ {1}}标识符仅更改所需的元素。

$
相关问题