我有以下架构:
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');
删除项目时,我要从其数组包含该项目的所有用户中从favouriteItems
和userItems
删除其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
},
...
]
当我删除ID为id1
的项目时,我想要以下结果(必须从所有用户的数组id1
和favouriteItems
中删除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 实现这一目标?
答案 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`
});