簡體   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