来自另一个表的猫鼬验证值

时间:2018-06-23 00:16:37

标签: node.js mongodb mongoose mongoose-schema

  

这是我的产品表架构

let schema = new mongoose.Schema({
    title: {type: String, required: true},
    price: {type: Number, required: true},
    description: {type: String, required: true},
    sizes: {type: Object, required: true},
    offer: {type: Number, default: 0},
    images: {type: Array, required: true},
    deal: {type: Boolean, default: false},
    category: {
        _id: {type: Schema.Types.ObjectId, required: true},
        name: {type: String, required: true}
    },
    company_name: {type: String, required: true}
});
  

我要做什么

我正在尝试验证另一个名为category.name的表中是否存在Category值相等。

1 个答案:

答案 0 :(得分:2)

可以使用异步验证器并查询类别集合。这样的事情(使用promise sytax作为验证器):

let schema = new mongoose.Schema({
  title: {type: String, required: true},
  price: {type: Number, required: true},
  description: {type: String, required: true},
  sizes: {type: Object, required: true},
  offer: {type: Number, default: 0},
  images: {type: Array, required: true},
  deal: {type: Boolean, default: false},
  category: {
      _id: {type: Schema.Types.ObjectId, required: true},
      name: {
        type: String, 
        required: true,

        validate: function(nameVal) {
          return new Promise(function(resolve, reject) {
            let Category = mongoose.model('Category');  //you would have to be sure that Category model is loaded before this one.  One reason not to do this        
            Category.findOne({name: nameVal}, (err, cat) => resolve(cat ? true : false));  //any non null value means the category was in the categories collection
          });
        }

      }
  },
  company_name: {type: String, required: true}
});

对此有一些想法:

  1. 这在http://mongoosejs.com/docs/validation.html#async-custom-validators上有记录。
  2. 如此处所述,默认情况下,验证程序不是运行 。有很多需要注意的地方。
  3. 根据我使用NoSQL DB的经验,创建新产品的代码将确保确保分配的类别有效。该代码可能在某个时候从数据库中找到了类别。因此,进行验证器查找将是多余的。但是您可能会遇到这样的情况,您有很多代码可以创建产品并希望在一处进行验证。
  4. 当我看到您将{_id:...,name:...}的文档存储为Product模式中的类别字段时,我想您可能希望这样做:

    ...
    category: {Schema.Types.ObjectId, ref: 'Category'},
    

    这使您可以存储对从categorys集合中检索到的类别的引用。如果在查询中使用填充方法,则猫鼬将在检索产品时为您内联加载类别文档。参见http://mongoosejs.com/docs/populate.html。填充功能有很多选项,您可能会觉得有用。据我所知,不会验证类别在保存时是否有效。但是,如果采用这种方法,则在保存之前,您已经在代码中先前查找了类别(请参阅链接以更好地理解我的意思)。从本质上讲,这使您可以像使用MongoDB一样进行联接,并获得存储节省和人们期望从“规范化”中获得的其他好处。