如何为对象数组定义猫鼬模式?

时间:2018-10-17 09:21:57

标签: mongoose mongoose-schema

我想创建一个猫鼬模式来保存每个用户的几张照片。

我知道如何为单张照片定义架构:

const mongoose = require('mongoose');
  const Schema = mongoose.Schema;

   const PhotoSchema = new Schema({

    user: {
      type: Schema.Types.ObjectId,
      ref: 'users'
    }, 

    imgId :{
      type: Number,
    }

    isProfileImg: {
      type: Boolean,
      default: true,
    },

    visible: {
      type: String,
    },   

});


  module.exports = Photo = mongoose.model('Photo', PhotoSchema);

但是我想知道如何概括该架构以容纳多张照片,每张照片都具有与上面相同的字段(imagIdisProfilePImgvisible)?

1 个答案:

答案 0 :(得分:1)

尝试以下模式:

const PhotoSchema = new Schema({

  user: {
    type: Schema.Types.ObjectId,
    ref: 'users'
  },
  photos: [
    {
      imgId: {
        type: Number,
      },
      isProfileImg: {
        type: Boolean,
        default: true,
      },
      visible: {
        type: String,
      }
    }
  ]
});