简体   繁体   English

限制架构参考猫鼬

[英]Limit Schema Ref Mongoose

I have a Schema Device with the following property 我有一个具有以下属性的模式设备

user : { type: Schema.Types.ObjectId, ref: 'User', required: true }

and another Schema User with the following property: 和另一个具有以下属性的模式用户

device : [{ type: Schema.Types.ObjectId, ref: 'Device' }]

is it possible to limit the number of devices the user could have to 3? 是否可以将用户必须拥有的设备数量限制为3个?

Yes. 是。 What you need to do is add one validate property and pass validation function and the error message if the size exceed the max length Here I have given one function with the limit of 10. You can change it as per your requirement. 您需要做的是添加一个validate属性,如果大小超过最大长度,则通过验证函数并返回错误消息。在这里,我给了一个函数,其限制为10。您可以根据需要进行更改。

var UserSchema = new Schema({
    device: {
      type: [{
        type: Schema.Types.ObjectId,
        ref: 'Device'
      }],
      validate: [limit, '{PATH} exceeds the limit of 10']
    }
  });

function limit(val) {
    return val && val.length <= 10;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM