如何从Mongoose模型node.js中删除对象

时间:2018-03-18 12:28:35

标签: javascript node.js mongoose mongoose-schema

我有一个使用express和mongoose的node.js应用程序。

我有一个listItem的模型,它是List的孩子,是User的孩子。当用户将listItems中的一个标记为已购买时,我成功添加到ListItem模型。

E.g。这是 listItem 模型:

var mongoose = require("mongoose");

var listItemSchema = mongoose.Schema({
    text: String,
    url: String,
    bought:Boolean,
    boughtBy: {
        name: String,
        id: {
         type: mongoose.Schema.Types.ObjectId,
         ref: "User"
        }
    }
});

module.exports = mongoose.model("ListItem", listItemSchema);

这是添加标记为已购买的用户的代码(它在FindByIDAndUpdate()函数中)

//Add that it was bought and who bought it into model
updatedListItem.bought = boughtFlag;
updatedListItem.boughtBy.id = boughtByID;
updatedListItem.boughtBy.name = boughtByName;

//save model to DB
updatedListItem.save();

因此,此代码有效,listItem模型成功显示购买它的用户的ID和名称。但是,我现在希望能够从对象中移除该用户,如果他们"取消标记"

我在下面尝试过这个,但无济于事。当用户点击" Unmark&#34 ;?时,如何从模型中删除boughtBy数据? 试过这个:

$pull: {
  boughtBy: req.params.item_id 
}

1 个答案:

答案 0 :(得分:0)

要从文档中删除特定字段,您可以使用$unset operator

ListItem.findOneAndUpdate(query, { "$unset": { "boughtBy": "" }}, options, callback)

我们可以在一个查询中更改买入的布尔值并删除buyBy字段:

ListItem.findOneAndUpdate(query, { "$unset": { "boughtBy": "" }, "$set": { "bought": false } }, options, callback)