猫鼬:如何推入嵌套数组?

时间:2018-01-17 23:43:03

标签: node.js mongodb mongoose nosql

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

mongoose schema

我需要在车辆阵列中插入,更新和删除文档。

到目前为止我尝试了什么:

添加:(工作)

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

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

由于

1 个答案:

答案 0 :(得分:1)

您可以考虑为VehicleGroupsvehicles设置单独的ObjectId,并通过Companies schema中的VehicleGroups: [{ _id: { type: Schema.Types.ObjectId, ref: 'vehicleGroup' }, // All other properties here vehicles: [{ type: Schema.Types.ObjectId, ref: 'vehicle' }] }] 引用它们:< / p>

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

vehicles

由于您VehicleGroups引用了ObjectIddocument,因此更新该引用所需要做的就是更新相应collection中的document

但是,如果您删除array,则需要从Companies collection中的相应Deque<Map.Entry<String, RecordItemElement>> top = map.entrySet().stream() .takeWhile(e -> !givenKey.equals(e.getKey())) .collect(Collectors.toCollection(ArrayDeque::new)); 删除其引用。

看看这种方法是否更容易实现!

相关问题