在save()之前将null设置为mongo必填字段

我们怎么能在mongoose save()之前将null设置为mongo db required字段为null;

模式

    a = new Schema({ 
      conn : {type: Object, required: true}
    })

    a.findOne(findQuery, (err, b) => {
      if(err)
        console.log(error);
      if(!b)
        console.log(errMessage);
       b.conn = null;
       b.save((err) => {
       if(err)
        console.log(err)
       -----something else----
       }
})
0
投票

在架构中使用default:{},因此如果没有传递值,则在保存文档时将采用默认的空对象。

您的架构应该是:

 a = new Schema({ 
      conn : {type: Object, required: true , default:{}}
    });

在检查记录时,可以检查conn对象的长度,如果对象长度为0,则表示数据库中不存在键值对。

if(Object.keys(conn).length==0){
  // conn object is empty , set new key 
   conn.your_key=your_value;
  // save the document
}else{
  // conn object is not empty 
}
0
投票

是的,它很可能,但您不应指定null值,您应该省略一个字段,换句话说,该字段不应在MongoDB文档中指定。解决方案是,你可以添加sparse索引。我不知道它是否适用于required标签但它适用于unique字段肯定你可以参考sparse

 a = new Schema({
  conn : {
     type: Object, 
     unique: true, 
     sparse: true
  }

});