sahil
sahil

Reputation: 19

want to push value in nested array in mongo using nodejs

I have a nested array "orders" in my collection "customers" array. I want to push value in orders corresponding to particular _id. How to do it using nodejs ?
This is how my array looks like. My collection name is "customers".

  {
        "_id":"5a696e875dceae1e40da3c00",
        "name":"John",
        "address":"6lacewood crescent road",
    "city":"Toronto",
    "state":"Ottawa",
    "email":"[email protected]",
    "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
    }
    ]

I want to push another order in orders array. How to do it using 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')    
});

       });
});

Upvotes: 0

Views: 365

Answers (2)

Saravana
Saravana

Reputation: 12817

using 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')    
})

Upvotes: 0

harpreet cheema
harpreet cheema

Reputation: 165

This is used for add new order in customer object

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

You can use this way for edit order from customer object

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

Upvotes: 1

Related Questions