【问题标题】:Mongoose: How to push in nested array? [duplicate]Mongoose:如何推入嵌套数组? [复制]
【发布时间】:2018-06-26 23:08:11
【问题描述】:

我对 NoSQL 世界很陌生。这是我的 Mongoose 架构的屏幕截图。

我需要在车辆数组中插入、更新和删除文档。

到目前为止我所做的尝试:

添加:(工作中)

Companies.findOne({'mobile' : givenMobileNumber, 'VehicleGroups.vehicle_group_id' : vehicleGroupId}, (err, res) => {
    if( err  || res == null) {
        callback(err, res);
    }else{

        var len =  res.VehicleGroups.length;
        for(var i=0; i<len; i++)
        {
            if(res.VehicleGroups[i].vehicle_group_id == vehicleGroupId)
                res.VehicleGroups[i].vehicles.push(data);
        }
        res.save(callback);
    }
})

删除:(工作中)

Companies.findOneAndUpdate({ mobile : givenMobileNumber, 'VehicleGroups.vehicle_group_id' : vehicleGroupId},
{ $pull : {'VehicleGroups.$.vehicles' : { 'vehicle_id' :  vehicleId} } }, callback);

仍在努力更新数据。我的方法有效吗?

谢谢

【问题讨论】:

  • 您应该向社区展示您的尝试以及失败的地方。尝试提出一个最小、完整且可验证的示例。 stackoverflow.com/help/mcve
  • @GregSchmit 我已经更新了我的问题。谢谢
  • 这是一个更好的问题!如果没有人回答并且您弄明白了,请随时answer your own question,因为当前的 IMO 是不可接受的。这样,如果其他人有这个问题,他们将更有可能找到它。
  • @Veeram 抱歉提及,但我被卡住了。
  • 抱歉,没有收到通知。我碰巧偶然发现了你的帖子。对于插入,您可以尝试Companies.findOneAndUpdate({ mobile : givenMobileNumber, 'VehicleGroups.vehicle_group_id' : vehicleGroupId}, { $push: {'VehicleGroups.$.vehicles' : data } }, callback);。要更新车辆,您可以使用 arrayFilters(从 3.6 开始提供)Companies.findOneAndUpdate( { mobile : givenMobileNumber}, { $inc: { "VehicleGroups.$[vg].vehicles.$[v].status": "new status" } }, { arrayFilters: [ { "vg.vehicle_group_id": vehicleGroupId } , { "v.vehicle_id":vehicleId} ], multi: true}, callback );

标签: node.js mongodb mongoose nosql


【解决方案1】:

您可以考虑为您的VehicleGroupsvehicles 设置单独的schemas,并在您的Companies schema 中通过ObjectId 引用它们:

VehicleGroups: [{
  _id: { type: Schema.Types.ObjectId, ref: 'vehicleGroup' },
  // All other properties here
  vehicles: [{ type: Schema.Types.ObjectId, ref: 'vehicle' }]
}]

将新的document 添加到VehicleGroup schema 之后会变成这样:

const newVehicleGroup = new VehicleGroup({
  name: 'New Vehicle',
  // Set all other fields
})

并将其添加到Companies schema:

Companies.findOneAndUpdate({
  mobile : givenMobileNumber, 'VehicleGroups.vehicle_group_id' : vehicleGroupId,
  { $push: { vehicleGroups: newVehicleGroup._id } }
})

由于您通过ObjectId 引用vehiclesVehicleGroups,因此更新该引用所需要做的就是更新相应collection 中的document

但是,如果您删除 document,则需要从 Companies collection 中的相应 array 中删除其引用。

看看这种方法是否让它更容易一些!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-19
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 2014-01-29
    相关资源
    最近更新 更多