mongoose 我可以要求在mongodb集合中设置一个属性吗?(不能为null)

bnl4lu3b  于 9个月前  发布在  Go
关注(0)|答案(4)|浏览(154)

我可以在mongodb中定义一个模式,它需要设置某些属性。就像SQL中的NOT NULL一样。如果可能的话。这是什么语法?
我正在使用node.js和mongoose。mongoose v3.6.15 mongodb v2.4.5

EditCharles A提供的答案是正确的,但通过查看文档,我发现在mongoose中也可以在schema defenition中定义一个字段,如下所示:

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

字符串

5sxhfpxr

5sxhfpxr1#

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

gr8qqesn

gr8qqesn2#

对于任何在这里找到他们的方式的人,你可以使用'required',这样:

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
    }
});

0vvn1miw

0vvn1miw3#

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

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

字符串
更多信息https://www.compose.com/articles/document-validation-in-mongodb-by-example/

iqxoj9l9

iqxoj9l94#

使用验证检查值为null或空,required属性检查仅未定义:

foo : {
    bar : {
        type : String,
        required : true,
        validation: (val) => ((val !== null) && (!!val.trim()))
    }
}

字符串

相关问题