繁体   English   中英

Mongoose,使用对象数组快速创建模式

[英]Mongoose, express- create schema with array of objects

我尝试创建包含对象数组的猫鼬模式。 架构看起来像:

const mapSchema = new Schema({
  name: {
    type: String
  },
  description: {
    type: String
  },
  rate: {
    type: Number,
    default: 0
  },
  sumOfRates: {
    type: Number,
    default: 0
  },
  places: [
    {
      name: String,
      description: String,
      difficulty: { type: String, default: 0 },
      sumOfRates: { type: String, default: 0 },
      lat: Number,
      lng: Number
    }
  ]
}, {
  timestamps: true
})

Places 是对象数组。 我尝试创建猫鼬模式并将其用作场所数组的元素(场所:[ref:'placeSchema'])。

const placeSchema = new Schema({
  name: {
    type: String
  },
  description: {
    type: String
  },
  difficulty: {
    type: Number,
    default: 0
  },
  lat: {
    type: Number
  },
  lng: {
    type: Number
  }
})

但我认为它会在 mongo(places document) 中创建另一个单独的文档。 是吗? 我尽量避免这种情况为了将它保存在一个文档中。现在(上面粘贴的代码),当我尝试在邮递员中插入 json 时,给了我一个错误:

{
    "name": "ergergergg",
    "description": "rgergrg",
    "places": [
        {
            "name":"cvcv",
            "description":"rgergrg",
            "lat":233,
            "lng":232
        }]
}

错误:

ValidationError: places: Cast to Array failed for value "[object Object]" at path "places"

为什么会出现这样的错误? 如何解决这个问题?

合适的方法是使用子模式。

const subSchema = new Schema({
  name: {
    type: String,
  },
  description: {
    type: String,
  },
  difficulty: {
    type: Number,
    default: 0,
  },
  lat: {
    type: Number,
  },
  lng: {
    type: Number,
  },
});

const mapSchema = new Schema({
  name: {
    type: String,
  },
  description: {
    type: String,
  },
  rate: {
    type: Number,
    default: 0,
  },
  sumOfRates: {
    type: Number,
    default: 0,
  },
  places: [subSchema],
}, {
  timestamps: true
});

插入新数据

mapSchema.insert({
   name: "ergergergg",
   description: "rgergrg",
   places: [
        {
            name: "cvcv",
            description": "rgergrg",
            lat: 233,
            lng: 232,
        },
   ],
});

要使 subSchema 可选,您可以执行以下操作 @DanMossa :

    pages: {
        type: [subSchema],
        required: false
    },

暂无
暂无

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

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