【问题标题】:Deleting Subdocument from an array of schema从模式数组中删除子文档
【发布时间】:2020-09-06 20:16:00
【问题描述】:

我有一个用户架构,每个用户都有一个个人资料,其中他有一个书籍集合,并且用户想从 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)

    });
});

【问题讨论】:

标签: javascript node.js mongodb mongoose nosql


【解决方案1】:

如果您需要从单个用户中删除,为什么不使用 updateOne 或 UpdateMany 从 bookcollection 中提取图书

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)
});

【讨论】:

  • 嘿!感谢您的帮助!我在 Mongoose 文档的解决方案中找到了另一个查询,我发现了这个代码 user1.bookCollection.pull({ _id:id});。它适用于我,但是当我在删除后再次尝试拉动时,它没有显示任何错误。如何使用单个id可以删除两次。错误是什么? ;)
  • 可以分享一下文档链接吗
  • 这里是链接:mongoosejs.com/docs/api/…
猜你喜欢
  • 1970-01-01
  • 2013-07-23
  • 2023-03-28
  • 1970-01-01
  • 2021-02-10
  • 2014-12-02
  • 2017-08-22
  • 2021-11-18
  • 1970-01-01
相关资源
最近更新 更多