【问题标题】:How to add multiple properties of the same type object in mongoose schemas如何在猫鼬模式中添加相同类型对象的多个属性
【发布时间】:2020-04-14 14:11:33
【问题描述】:

如何在我的 moongoose 架构中为我的电影添加多个 (1,2,3...x) 类型?

我在电影模式中使用了这个流派模式:

const genreSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 50
  }
});

电影架构:

const Joi = require('joi');
const mongoose = require('mongoose');
const {genreSchema} = require('./genre');


const Movie = mongoose.model('Movie', new mongoose.Schema({
  title:  {
    type: String,
    required: true,
    trim: true,
    minlength: 5,
    maxlength: 255,
  },
  genre: {
    type: genreSchema,
    required: true
  },
  numberInStock: {
    type: Number,
    required: true,
    min: 0,
    max:255
}
}));

function validateMovie(movie) {
  const schema = {
    title: Joi.string().min(3).required(),
    genreId: Joi.objectId().required(),
    numberInStock: Joi.number().min(0).required(),
  };

  return Joi.validate(movie, schema);
}

我还想用 Joi 验证架构。

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    种类繁多?你可以这样定义你的模型:

     genre: [{
        type: genreSchema,
        required: true
      }],
    

    【讨论】:

    • 谢谢,我不知道这是可能的。关于我的 rest api 和我的 post/put 函数,我对该方法还有其他问题,但这将超出这个问题的范围。我应该开一个新的吗?
    • 哈,很高兴我能帮上忙!是的,如果您有其他问题,您应该创建另一个问题
    猜你喜欢
    • 2019-11-20
    • 1970-01-01
    • 2017-09-10
    • 2011-11-14
    • 2018-06-08
    • 2021-08-16
    • 2016-08-25
    • 2021-05-31
    • 2012-01-14
    相关资源
    最近更新 更多