从架构数组中删除子文档

编程入门 行业动态 更新时间:2024-10-05 11:13:53

从<a href=https://www.elefans.com/category/jswz/34/1771112.html style=架构数组中删除子文档"/>

从架构数组中删除子文档

我有一个用户模式,每个用户都有一个配置文件,在该配置文件中他拥有一本书的集合,并且该用户想从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)
});

更多推荐

从架构数组中删除子文档

本文发布于:2024-05-07 21:36:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1757357.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:架构   组中   文档

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!