使用Mongoose和express创建包含对象数组的模式(schema)

8

我尝试创建包含对象数组的mongoose模式。模式如下:

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是一个对象数组。我尝试创建mongoose模式,并将其用作places数组的元素(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文档)。是这样吗?我试图避免这种情况,将其保留在一个文档中。现在(上面贴的代码)在postman中尝试插入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"

为什么会出现这样的错误?如何修复呢?

2个回答

20

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

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,
        },
        {
            name: "22",
            description: "erwer2",
            lat: 123,
            lng: 321,
        },
   ],
});

2
这是一个非常有用的答案。谢谢,它基本上解决了我的问题。我只有一个问题,如何使places数组可选?谢谢。 - ThisIsNotAnId
@ThisIsNotAnId 你最终解决了这个问题吗? - DanMossa

3
为了使子模式是可选的,您可以尝试像这样做@DanMossa:
    pages: {
        type: [subSchema],
        required: false
    },

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接