简体   繁体   中英

mongoose/javascript: Can't update collection in Mongodb

This is my db schema

 let couponId = Schema({ RestaurantId: { type: String }, RestaurantName: { type: String }, RestaurantLocation: { type: String }, AssignedTo: Schema.Types.Mixed, CouponValue: { type: [String] } }); 

I want to update the AssignedTo field with a value of array of objects with a dynamic key and a value. I am performing this query

 CouponId.findOne({ "RestaurantId": resId }, (err, restaurant) => { value.push({ [userNumber]: restaurant.CouponValue[0] }); console.log(value); restaurant.update({ "RestaurantId": resId }, { $set: { "AssignedTo": value } }, function(err) { if (err) { console.log(err); } else { console.log("updated"); } }); }); 

The query, when executed, is giving the result of updated in console but its not getting updated in db. If this query is converted to MongoShell query and executed, it gives the result and collection is getting updated, where mongoShell query i am running is

db.couponids.update({"RestaurantId" : "1234"},{$set:{"AssignedTo":[{"1234":"2345"}]}});

Where am i going wrong?

restaurant is the output from the first collection and doesn't have any update function in it... So, You need to keep the same collection name from which you have done findOne

CouponId.update({
    "RestaurantId": resId
  }, {
    $set: {
      "AssignedTo": value
    }
  }, function(err) {
    if (err) {
      console.log(err);
    } else {
      console.log("updated");
    }
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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