【问题标题】:How to remove an object from a Mongoose model node.js如何从 Mongoose 模型 node.js 中删除对象
【发布时间】:2018-03-18 20:46:19
【问题描述】:

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

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

例如这是 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 和名称。但是,如果他们“取消标记”,我现在希望能够从对象中删除该用户

我一直在下面尝试此操作,但无济于事。当用户单击“取消标记”时,如何从模型中删除 boughtBy 数据? 试过这个:

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

【问题讨论】:

    标签: javascript node.js mongoose mongoose-schema


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2016-10-26
      • 2021-10-28
      • 2019-02-02
      • 1970-01-01
      • 1970-01-01
      • 2020-02-27
      • 2021-07-01
      • 2012-11-25
      相关资源
      最近更新 更多