【问题标题】:set field as empty for mongo object using mongoose使用 mongoose 将 mongo 对象的字段设置为空
【发布时间】:2012-09-20 03:46:32
【问题描述】:

我在一个对象上调用 user.save(),我在其中设置了 user.signup_date = null;

user.first_name = null;
user.signup_date = null;

user.save();

但是当我在 mongodb 中查看用户时,它仍然设置了 signup_date 和 first_name...如何有效地将此字段设置为空或 null?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    要从现有文档中删除这些属性,请在保存文档之前将它们设置为 undefined 而不是 null

    user.first_name = undefined;
    user.signup_date = undefined;
    
    user.save();
    

    确认仍在 Mongoose 5.9.7 中工作。请注意,您尝试删除的字段仍必须在您的架构中定义才能正常工作。

    【讨论】:

    • 非常好的答案节省了我很多时间:)
    • 如果filed是一个数组,它不是工作怎么办:(
    • @AnilYadav 数组字段由 Mongoose 专门处理,应该始终存在(当然也可以为空)。
    • 这仍然是一个有效的答案吗?我正在使用 mongoose 5.5.11、mongo 3.6 并将字段设置为未定义不会删除该字段,它会将其设置为 null
    • @faniva 是的,我刚刚确认它仍在 5.9.7 中工作。请注意,您尝试删除的字段仍必须在您的架构中定义。
    【解决方案2】:

    如果您尝试使用 set 方法是否会有所不同,如下所示:

    user.set('first_name', null);
    user.set('signup_date', null);
    user.save();
    

    或者可能是保存的时候出错了,如果这样做会发生什么:

    user.save(function (err) {
        if (err) console.log(err);
    });
    

    它会在日志中打印任何内容吗?

    【讨论】:

      【解决方案3】:

      另一种选择是将这些属性的默认值定义为undefined

      类似于以下内容:

      let userSchema = new mongoose.Schema({ first_name: { type: String, default: undefined }, signup_date: { type: Date, default: undefined } })

      【讨论】:

      • 仅在 type:Array 和 type:Map 上需要,但是很好的提示!!
      【解决方案4】:

      只需删除字段

      delete user.first_name;
      delete user.signup_date;
      user.save();
      

      【讨论】:

      • 你可以先试试这个:user = user.toObject()
      【解决方案5】:

      Mongoose documentation(架构类型)上,您可以转到Arrays 的说明。在那里,它说:

      数组是特殊的,因为它们隐含的默认值为[](空数组)。

      var ToyBox = mongoose.model('ToyBox', ToyBoxSchema);
      console.log((new ToyBox()).toys); // []
      

      要覆盖此默认值,您需要将default 值设置为undefined

      我在 toys 元素中添加了一个内容

      var ToyBoxSchema = new Schema({
           toys: {
                type: [{
                    name: String,
                    features: [String]
                }],
                default: undefined
           }
      });
      

      【讨论】:

        猜你喜欢
        • 2015-05-25
        • 2019-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-01
        • 2020-07-29
        • 1970-01-01
        • 2016-06-06
        相关资源
        最近更新 更多