set field as empty for mongo object using mongoose

后端 未结 5 768

I\'m calling user.save() on an object, where I set user.signup_date = null;

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

user.save();

相关标签:
5条回答
  • 2020-12-01 11:15

    Another option is to define a default value as undefined for these properties.

    Something like the following:

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

    0 讨论(0)
  • 2020-12-01 11:16

    To remove those properties from your existing doc, set them to undefined instead of null before saving the doc:

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

    Confirmed as still working in Mongoose 5.9.7. Note that the field you're trying to remove must still be defined in your schema for this to work.

    0 讨论(0)
  • 2020-12-01 11:17

    Just delete fields

    delete user.first_name;
    delete user.signup_date;
    user.save();
    
    0 讨论(0)
  • 2020-12-01 11:31

    Does it make a difference if you try the set method instead, like this:

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

    Or maybe there's an error when saving, what happens if you do:

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

    Does it print anything to the log?

    0 讨论(0)
  • 2020-12-01 11:32

    On Mongoose documentation (Schema Types), you can go to the Arrays explanation. There, it says this:

    Arrays are special because they implicitly have a default value of [] (empty array).

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

    To overwrite this default, you need to set the default value to undefined

    (I've made an addition inside the toys element)

    var ToyBoxSchema = new Schema({
         toys: {
              type: [{
                  name: String,
                  features: [String]
              }],
              default: undefined
         }
    });
    
    0 讨论(0)
提交回复
热议问题