如何为具有子项的属性分配“null”或“undefined”,以mongoose为单位

问题描述 投票:1回答:1

如果我没有在mongoose中初始化它,我想使“地址”属性为“null”或“undefined”。我试图将其初始化为空值但不起作用。

var userSchema = new Schema({
    name: { type: String, default: null },
    address: {
      number: { type: String, default: null },
      route: { type: String, default: null },
      areaInner: { type: String, default: null },
      areaOuter: { type: String, default: null },
      country: { type: String, default: null }
    }
},{timestamps:true});

var User = mongoose.model('users', userSchema);

var newUser = User({
        name: name,
        address:null
});

newUser.save();
node.js mongodb mongoose schema subdocument
1个回答
0
投票

您必须为“地址”定义其他架构:

var addressSchema = new Schema({
  number: {type: String, default: null},
  ...
}); 

var userSchema = new Schema({
  name: {type: String, default: null},
  address: {type: addressSchema, default: null}
});