删除数组中所有出现的ObjectId

时间:2018-12-04 21:48:38

标签: node.js mongodb mongoose

我有以下架构:

var userSchema = new mongoose.Schema({
    username: {type: String, required: true},
    favouriteItems: [{type: mongoose.Schema.Types.ObjectId, ref: 'Item'}],
    userItems: [{type: mongoose.Schema.Types.ObjectId, ref: 'Item'}]
});

var itemSchema = new mongoose.Schema({
    name: {type: String, required: true},
    price: {type: Number, required: true}
});

mongoose.model('User', userSchema , 'Users');
mongoose.model('Item', itemSchema , 'Items');

删除项目时,我要从其数组包含该项目的所有用户中从favouriteItemsuserItems删除其ObjectId。

示例:

初始:

Users:
[
    {
        _id: "a",
        username: "username1",
        favouriteItems: ["id1"],
        userItems: ["id2", "id3"]
    },
    {
        _id: "b",
        username: "username2",
        favouriteItems: ["id2"],
        userItems: ["id1", "id4"]
    },
    ...
]

Items:
[
    {
        _id: "id1",
        name: "item1",
        price: 19
    },
    {
        _id: "id2",
        name: "item2",
        price: 7
    },
    ...
]

当我删除I​​D为id1的项目时,我想要以下结果(必须从所有用户的数组id1favouriteItems中删除userItems):

Users:
[
    {
        _id: "a",
        username: "username1",
        favouriteItems: [],
        userItems: ["id2", "id3"]
    },
    {
        _id: "b",
        username: "username2",
        favouriteItems: ["id2"],
        userItems: ["id4"]
    },
    ...
]

Items:
[
    {
        _id: "id2",
        name: "item2",
        price: 7
    },
    ...
]

如何使用猫鼬 node.js 实现这一目标?

1 个答案:

答案 0 :(得分:0)

您应该看一下post mongoose middleware hooks,尤其是remove上的钩子:

itemSchema.post('remove', async function(doc) {
  // doc is removed ... execute query to remove from favorites using the `doc._id`
});