如何在猫鼬的其他对象数组中更新特定对象的元素

时间:2018-10-12 20:01:50

标签: node.js mongodb express mongoose

我需要更新文档中属于数组的对象的元素。具体来说,“更新集合中特定用户的特定订单的状态”

我在集合中具有要编辑的用户的用户名,要编辑的数组中的订单的orderID以及newStatus。...

这里是架构和猫鼬代码...

USER: {
  _id: objectId(as425as4526dc)
  username: 'admin',
  password: 'a61a8726ahf604s',
  fname: 'first',
  lname: 'last',
  date: '2018-9-9',
  orders: [
    {
       _id: objectID(012eoisadn3)
       status: 0,
       name: 'name'
       description: 'hello'
    }
  ]
 }

MONGOOSE

  const username = req.body.username;
  const orderID = req.body.id;
  const newStatus = req.body.status;

  User.update(
    {
      username: username,
      'orders._id': orderID
    },
    {
      $set:{
        'orders.$.status': newStatus
      }
    },
    function(err,docs){
     ...
     //Do Stuff Here
     ...
    }
  );

退货

{ n: 0,
  nModified: 0,
  opTime:
   { ts: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1539373723 },
     t: 1 },
  electionId: 7fffffff0000000000000001,
  ok: 1,
  operationTime: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1539373723 },
  '$clusterTime':
   { clusterTime: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1539373723 },
     signature: { hash: [Object], keyId: [Object] } } }

0 个答案:

没有答案