无法使用猫鼬更新子文档

时间:2020-08-30 20:49:51

标签: javascript node.js mongodb typescript mongoose

当我尝试用猫鼬更新子文档中的数据时遇到问题

这是数据模型:

{ status: 'regular',
  devices:
   [ { ip: 'deviceIp',
       active: true,
       _id: 5f4c05cb4708cf0e37a68ac0,
       name: 'deviceName',
       os: 'deviceOs',
       refreshToken:
        'eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCIsImtpZCI6IjEifQ.eyJ1c2VyIjoidGVzdFVzZXIiLCJtYWlsIjoidGVzdEB1c2VyLmNvbSIsImlhdCI6MTU5ODgxNzczOSwibmJmIjoxNTk4ODE3NzQxLCJleHAiOjE2MDE0MDk3MzksImF1ZCI6Im15YXVkIiwiaXNzIjoibXlpc3N1ZXIiLCJzdWIiOiJ2IiwianRpIjoiMSJ9.di6BeKZV5OufLEY8Hnk_nC_vcCsVZZ_XJecUc1h695hDbFlgxTtNOZoi-e3uvAkckclfAKjJk7T-osEGohsnfpdA07XDH3pOniGYHVw_k1u-e6-0pu9YpSop6cv7cnlsR-50QjE9vmzg4F1mBy2ZYVCp6GSfg46duXjStUOamUM30AYElSSVX5EMsK1uBg2tfVipV8xRhHCZIIdYNr-xq8G5CcZ1lEIQrtkC2ljU7roLpC5pejZ-JkaHSNNKwVARW7JuLNbb4FaSAjv_AE87faozPWAbdgXIaap8A5nLeH_-XJhwJDIIRGnwwsJM969DaTVee2F40lUfBzhugmffeg',
       loginDate: 2020-08-30T20:02:19.257Z } ],
  _id: 5f4c05c64708cf0e37a68abf,
  username: 'testUser',
  password: 'Xa8S8qxXsQqAvenX5Kk4BloZfX1XePosVCNXoyLBQz4=',
  mail: 'test@user.com',
  salt: 'hDsCu0CShRbE/XFAvw6y/8SLu4vufP7a7ewiCBLXIQ0=',
  __v: 3 }

这是我在TS中所做的:

let userQuery = await UserModel.find({

  "devices.refreshToken": refreshToken,
  "devices.active": true

});

let userInfo:any = userQuery[0];

if(!userInfo){

  reject("Invalid token");
  return;

}

let device = userInfo.devices.filter(_device => _device.refreshToken == refreshToken)[0];

userInfo.updateOne( { _id: userInfo._id , "devices._id": device._id},{ $set: {"devices.$.active":false} });

每个设备都是这样生成的:

let userDevice = new DeviceModel({

  ...device,
  refreshToken,
  active:true,

});

userInfo.devices.push(userDevice);

问题在于,即使查询正常运行,devices数组中的数据也永远不会更新

1 个答案:

答案 0 :(得分:0)

我建议您首先使用代码中的 mongoDB 来检查查询,例如使用 Robo 3T:

对于您的情况,请尝试以下操作:

db.getCollection('YOUR COLLECTION NAME HERE').updateOne({ '_id': 5f4c05c64708cf0e37a68abf ,'devices._id': 5f4c05cb4708cf0e37a68ac0 }, { $set: { 'devices.$.active': false }});