【问题标题】:How can I save a record to mongoDB by skipping a field which is marked as required in the Mongoose schema in nodejs?如何通过跳过在 nodejs 的 Mongoose 模式中标记为必需的字段来将记录保存到 mongoDB?
【发布时间】:2020-05-23 20:24:24
【问题描述】:

我有一个模式,其中一个字段被标记为必填,我有许多记录要插入到 db 但一条记录没有标记为必填的字段,但我也想插入该记录而不输入数据到按要求标记的文件。有没有可能我可以以这种方式插入数据库。我如何通过提供所需的错误字段来管理该记录。

fi

e
ld2: {
          type: String,
          required: function() {
            if(this.field2) { return true }
            else return false
          }
        }
        //trying to insert the data from controller
        //some code..
        let jsonData ={field2 :"",field2 :'abcd'}
        var test = new SchemaTest()//creating schema instance
        for(var i in jsonData)
        //for below code for first iteration field2  have no data, 
        //second have data
        test.field2 = jsonData.field2 
        test.save((err,test)=> {})

【问题讨论】:

  • 你说的是哪个数据库?
  • 我正在尝试保存到 mongodb
  • 使用insert怎么样?它会跳过验证。
  • 是否可以使用“插入”将模式实例插入数据库,保存和插入是否起到相同的作用,除了插入跳过验证?
  • 检查this 的差异

标签: node.js mongodb schema


【解决方案1】:

可能的做法是删除必填字段。如果不是所有记录都会填写该字段,则不应按要求进行设置。 如果其他属性变为真,您可以使用 if 语句将其设置为真。

//Other code.
field1 :{
  type: Boolean,
  required: true
},
field2: {
  type: String,
  required: function() {
    if(this.field1) { return true }
    else return false
  }
}
// Rest of code

【讨论】:

  • 我已经使用您的解决方案对我的代码进行了一些更改,请您检查它是否正确?
  • 你有链接吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-23
  • 1970-01-01
  • 2019-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-07
相关资源
最近更新 更多