简体   繁体   English

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

[英]Remove multiple records from a collection- MongoDB

I have two models with the following schemas: 我有两个具有以下架构的模型:

Map: 地图:

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'}]
});

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

As you can see, one map has many devices. 如您所见,一张地图有很多设备。 Now, When I delete a map, I want to delete all of the devices that belong to it. 现在,当我删除地图时,我想删除属于它的所有设备。 This should be easy because each map has an array of it's device ID's. 这应该很容易,因为每个地图都有其设备ID的数组。 But I can not seem to find a way to delete multiple records from a collection at once. 但是我似乎找不到一种立即从集合中删除多个记录的方法。 I delete my map with this function: 我使用以下功能删除地图:

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

};

This returns the map so I can access it's device ID's as map.devices. 这将返回地图,因此我可以将其设备ID作为map.devices进行访问。 However, how can I now use map.devices to remove all of these from the device collection? 但是,现在如何使用map.devices从设备集合中删除所有这些? I was thinking something like device.remove(map.devices) ? 我在想类似device.remove(map.devices)的东西吗?

You can first find the map object and use the array of device _id s with the $in operator to remove all the devices in the map. 您可以首先找到地图对象,并使用$in _运算符使用device _id数组来删除地图中的所有设备。 Below is some (untested) sample code. 以下是一些(未经测试的)示例代码。

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