想使用nodejs在mongo中推送嵌套数组中的值

时间:2018-01-30 04:31:40

标签: node.js mongodb

我的集合“customers”数组中有一个嵌套数组“orders”。我想在对应于特定_id的订单中推送价值。怎么用nodejs呢?
这就是我的数组的样子。我的收藏名称是“客户”。

  {
        "_id":"5a696e875dceae1e40da3c00",
        "name":"John",
        "address":"6lacewood crescent road",
    "city":"Toronto",
    "state":"Ottawa",
    "email":"john@example.com",
    "zipcode":"123456",
    "gender":"1",
    "orders": [
    {
    "product":"Basket",
    "date":"2014-09-13T18:30:00.000Z",
    "Quantity":1,
"Unitprice":29.99
    },
    {
    "product":"Basket",
    "date":"2014-08-31T18:30:00.000Z",
    "Quantity":2,
"Unitprice":29.99
    },
    {
    "product":"Controller",
    "date":"2014-08-13T18:30:00.000Z",
    "Quantity":3,
"Unitprice":39.99
    }
    ]

我想在订单数组中推送另一个订单。如何使用nodejs?

的NodeJS

app.post('/addorders:id', function(req, res, next){

   console.log(req.params.id);

    var body = req.body;
        console.log('update command');
       dbConn.then(function(db) {


       var dd = db.db("customermanagement");
  console.log('update command');
       dd.collection("customers").findByIdAndUpdate( ObjectId(req.params.id), {$push : {orders : body}}, function(err,doc){
    if(err) console.error(err)    
    console.log('pushed')    
});

       });
});

2 个答案:

答案 0 :(得分:1)

这用于在客户对象中添加新订单

var cond = {
              _id: ObjectId("5a587b0ca3f8b34cc3f3cfe4"),//CustomerID
           };
var set = {
             $push: {
                order: {
                      product: "xyz",
                      Quantity: 5, 
                      Unitprice:10                 
                   }
             }
       };

您可以使用这种方式从客户对象

编辑订单
var cond = {
         _id: ObjectId("5a587b0ca3f8b34cc3f3cfe4"),// Here customer ID is a _id of customer object
         "orders": {
              $elemMatch: { _id: ObjectId("5a587b0ca3f8b34cc3f3cfe5") }//Here You can match _id of object array of customer or you can match any other field.
          }
       };
var set = {
          $set: {
              "orders.$.product":"Abc"//Here you can also update multiple fields
          }
    };


Models. customers.findOneAndUpdate(cond, set, 
   function(err, res) {
        if (err) 
            console.log(err);
        else
            console.log(res)
 });

答案 1 :(得分:0)

使用findByIdAndUpdate

let id = ObjectId("5a6ff7cf7863fc1242ebf086") // change this to customer_id
let order = {product:"something"}

Customers.findByIdAndUpdate(id, {$push : {orders : order}}, function(err,doc){
    if(err) console.error(err)    
    console.log('pushed')    
})