在save()

时间:2019-01-25 13:04:37

标签: node.js mongodb mongoose

伙计们,如何在mongoose save()之前将null设置为mongo db必填字段设置为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----
       }
})

2 个答案:

答案 0 :(得分:0)

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

您的架构应为:

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

在检查记录时,您可以检查conn对象的长度,如果对象长度为0,则意味着db中不存在键/值对。

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 
}

答案 1 :(得分:0)

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

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

});

相关问题