简体   繁体   中英

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. 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. However, how can I now use map.devices to remove all of these from the device collection? I was thinking something like 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. 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);
        });
    });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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