繁体   English   中英

从集合中删除多个记录-MongoDB

[英]Remove multiple records from a collection- MongoDB

我有两个具有以下架构的模型:

地图:

var MapSchema = mongoose.Schema({
    ownerId:{
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    mapName: {
        type: String
    },
    mapImagePath:{
        type: String,
        required: true
    },

    createdAt: { type: Date, default: Date.now },

    devices: [{type: Schema.Types.ObjectId, ref: 'Device'}]
});

设备:

var DeviceSchema = mongoose.Schema({
    deviceName:{
        type: String,
        required: true,
        index: true,
        unique: true
    },
   roomCapacity: {
        type: Number
    },
    roomImagePath:{
        type: String,
    },
    mapId:{
        type: Schema.Types.ObjectId,
        ref: 'Map',
        required: true
    },
    coords:{
        type: [Number], //[xcoord, ycoord]
        required: true
    },
    status:{
        type: String,
        required: true,
        default: 'Available'
    },
    user:{
        type: String,
    },

    createdAt: { type: Date, default: Date.now }
});

如您所见,一张地图有很多设备。 现在,当我删除地图时,我想删除属于它的所有设备。 这应该很容易,因为每个地图都有其设备ID的数组。 但是我似乎找不到一种立即从集合中删除多个记录的方法。 我使用以下功能删除地图:

module.exports.deleteMap = function(mapId, callback){
    Map.findOneAndRemove({_id: mapId}, callback)

};

这将返回地图,因此我可以将其设备ID作为map.devices进行访问。 但是,现在如何使用map.devices从设备集合中删除所有这些? 我在想类似device.remove(map.devices)的东西吗?

您可以首先找到地图对象,并使用$in _运算符使用device _id数组来删除地图中的所有设备。 以下是一些(未经测试的)示例代码。

module.exports.deleteMap = function(mapId, callback) {
    Map.findOneAndRemove({_id: mapId}, function(dbErr, map) {
        if(dbErr) {
            return callback(dbErr);
        }

        Device.remove({_id: {$in: map.devices}}, function(dbErr) {
            if(dbErr) {
                return callback(dbErr);
            }

            return callback(undefined, map);
        });
    });
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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