如何在数组字段中设置Mongoose模式验证

时间:2018-10-16 06:15:20

标签: validation mongoose schema

最近几天,我遇到了猫鼬模式验证的问题。因为当我将数据放入评论数组时,当我将重复项放入数组时它没有显示任何错误。现在,我想在审阅数组字段中设置一个验证,该字段的合金名称字段将是唯一的。请参阅下面的架构。

var subSchema = mongoose.Schema({
    _id:String,
    name:{ type: String, unique:true},
    comment: String,
    stars: Number,
    date: String
},{ _id : true, index: true });

var NoteSchema = mongoose.Schema({
        title : { type: String, unique:true},
        slogan : String,
        description : String,
        stars : Number,
        category : String,
        img_url : String,
        price : Number,
        reviews: [subSchema]
}, {
    timestamps: true
});

数据如下所示:

{
    "reviews": [
      {
        "_id": "0",
        "name": "Rahim",
        "comment": "Rahim is a good writer",
        "stars": 5,
        "date": "16-10-2018"
      },
      {
        "_id": "1",
        "name": "Rahim",
        "comment": "Rahim is a good writer and",
        "stars": 5,
        "date": "16-10-2018"
      },
      {
        "_id": "2",
        "name": "Karim",
        "comment": "Karim is a good writer...",
        "stars": 5,
        "date": "16-10-2018"
      }
    ],
    "title": "Hello21",
    "slogan": "this is slogan2",
    "description": "This is description",
    "stars": 3.4,
    "category": "Story",
    "img_url": "img_url",
    "price": 220,
    "createdAt": "2018-10-08T08:24:29.528Z",
    "updatedAt": "2018-10-16T05:36:03.649Z",
    "__v": 0
  }

我想防止在评论数组字段中重复输入。

0 个答案:

没有答案