【问题标题】:Can I require an attribute to be set in a mongodb collection? (not null)我可以要求在 mongodb 集合中设置属性吗? (不为空)
【发布时间】:2013-07-30 09:33:34
【问题描述】:

我可以在 mongodb 中定义一个需要设置某些属性的模式吗?很像 SQL 中的NOT NULL。如果可能的话。这是什么语法?

我正在使用 node.js 和猫鼬。 猫鼬 v3.6.15 mongodb v2.4.5

编辑 Charles A 提供的答案是正确的,但是通过查看文档我发现在 mongoose 中也可以像这样在模式定义中定义一个字段:

foo : {
    bar : { type : String, required : true }
}

【问题讨论】:

  • 您使用的是哪个驱动程序?我知道如何在 java 中使用 spring。
  • @Jayz 回答更新问题...
  • @LudwigMagnusson 最好添加您自己的答案作为此问题的单独答案,然后接受使用required: true 是最好的方法。
  • @JohnnyHK 但我接受了查尔斯的回答,因为我解决了我的问题。之后我才将其更改为另一种格式。

标签: mongodb mongoose


【解决方案1】:

在 Mongoose 中,您可以使用 validator 在保存之前检查字段是否已设置。据我所知,没有办法在 Schema 上指定一个字段是必需的,所以它需要更多的样板代码。

【讨论】:

    【解决方案2】:

    对于必填字段,在集合的验证器中使用 $AND 和“$exists: true”:

    db.createCollection("foo", {
      validator: {
        $and: [ {"bar": {$type: "string", $exists: true}} ]
    })
    

    更多信息在这里 https://www.compose.com/articles/document-validation-in-mongodb-by-example/

    【讨论】:

      【解决方案3】:

      对于任何在这里找到自己的方式的人,您可以使用“必需”,例如:

      db.createCollection("person", {
         validator: {
            $jsonSchema: {
               bsonType: "object",
               required: [ "name" ],
               properties: {
                  name: {
                     bsonType: "string",
                     description: "must be a string and is required"
                  }
               }
            }
         }
      }
      

      您可以在文档中阅读更多内容,herehere

      注意,另一种方法是通过 mongoose 使用 Mongodb,它允许直接在字段级别指定:

      const person = new mongoose.Schema({
          name {
              type: String,
              required: true
          }
      });
      

      【讨论】:

      • 谢谢安德烈。另外,这里有一个关于模式所需属性的文档的链接 mongoosejs.com/docs/guide.html#storeSubdocValidationError 需要在保存之前调用person.validateSync() 进行验证。
      猜你喜欢
      • 2019-08-19
      • 2011-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-08
      • 1970-01-01
      • 2011-10-20
      • 2016-06-25
      相关资源
      最近更新 更多