node.js - Mongoose,express-使用对象数组创建模式

标签 node.js mongodb express mongoose

我尝试创建包含对象数组的 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 模式并将其用作地方数组的元素(地方:[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) 中创建另一个独立的文档。可以?我试图避免这种情况,将其保留在一个文档中。现在(上面粘贴的代码),当我尝试在 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"

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

最佳答案

适当的方法是使用子架构。

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,
        },
   ],
});

关于node.js - Mongoose,express-使用对象数组创建模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46302053/

相关文章:

mongodb - tar gzip mongo dump 像 MySQL

mysql - 如何拥有一个可以独立于 azure 运行的完全独立的应用程序?

node.js - 避免在 Express.js 中记录图像

node.js - 如何根据用户表单输入查询api

node.js - React 中删除请求

mongodb $nin on ObjectId 不起作用

node.js - 如何为非静态文件响应设置 max-age

node.js - React-Router 和 Meteor 无法在刷新时使用参数渲染路由

node.js - NodeJS 加密 RSA,与 Elixir/Erlang PublicKey 不兼容?

javascript - 从 node.js 和 Mongoose 中的回调返回值