简体   繁体   English

我如何在Mongodb,Node JS中更新数组的多个元素

[英]how can i update multiple elements of an array in Mongodb,node js

I need to update my complaints array object elements by complaints._id here is my mongo document. 我需要通过complaints._id来更新投诉数组对象元素。_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
}

I am trying this approach but it is not working what be do 我正在尝试这种方法,但不能正常工作

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);
            }
            });

        });

For your problem I suggest to use the simple update api and not the findByIdAndUpdate , cause you will not search by id but you will search by complaints._id , and then use the $ identifier to change only the needed element. 对于您的问题,我建议您使用简单的update api,而不要使用findByIdAndUpdate ,因为您不会按id搜索,但会按complaints._id搜索findByIdAndUpdate ,然后使用$标识符仅更改所需的元素。

CPS.update({
  "complaints._id": request.params.documentid
}, {
  "$set": {
    "complaints.$.status": "WAITING",
    "complaints.$.color": "#CE002D"
  }
}, 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);
    }
  });

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM