架构数组中删除子文档"/>
从架构数组中删除子文档
我有一个用户模式,每个用户都有一个配置文件,在该配置文件中他拥有一本书的集合,并且该用户想从bookCollection中删除一本书,我尝试将我的代码放在底部。用户架构如下:
var bookSchema = new Schema({
title: {
type: String,
required: true,
},
author: {
type: String,
required: true,
},
publisher: {
type: String,
default: "not set"
},
desc: {
type: String,
default: "not set"
},
availableAs: {
type: String, //either hardcopy or softcopy
required: true
},
price: {
type: Number,
default: 0
},
category: {
type: String,
default: "not set"
},
imageurl: {
type: String,
default: 'nobook.png'
},
bookurl: {
type: String,
default: ''
},
softcopy_available: {
type: Number,
default: 0
}
});
var userSchema = new Schema({
admin: {
type: Boolean,
default: false
},
bookCollection: [bookSchema]
});
这是我正在尝试的操作,但是删除不起作用,有时会显示错误,并且页面会继续加载。
router.post('/', (req, res, next) => {
console.log(req.body.bookid);
var id=req.body.bookid;
users.findOne({
})
.then((user1) =>
user1.bookCollection.pull(req.body.bookid._id);
})
.catch((err) => {
next(err)
});
});
回答如下:如果您需要从单个用户中删除,为什么不使用updateOne或UpdateMany从藏书中提取这本书?>
var ObjectId = mongoose.Types.ObjectId; users.updateOne({_id: ObjectId(user_id)},{ $pull: { bookCollection: { _id: ObjectId(req.body.bookid._id) } }}) .then((results) => // results of your update query }) .catch((err) => { next(err) });
如果要从所有用户中删除某本书籍,则>
var ObjectId = mongoose.Types.ObjectId; users.updateMany({},{ $pull: { bookCollection: { _id: ObjectId(req.body.bookid._id) } }}) .then((results) => // results of your update query }) .catch((err) => { next(err) });
更多推荐
从架构数组中删除子文档
发布评论