【问题标题】:Initialize Mongoose Schema from JSON从 JSON 初始化 Mongoose Schema
【发布时间】:2020-02-24 03:38:13
【问题描述】:

我有一些 JSON 数据正在通过 HTTP 正文进行 POST,如下所示:

{
  orderList: [
    { product: [Object], quantity: '1' },
    { product: [Object], quantity: '1' },
    { product: [Object], quantity: '1' },
    { product: [Object], quantity: '1' }
  ],
  user: {
    name: { first: 'John', middle: 'Jay', last: 'Dent' },
    address: {
      street1: '1 Easy Street',
      street2: '',
      city: 'Los Angeles',
      state: 'California',
      zip: '12345'
    },
    email: 'john@nocantack.com',
    phone: '123 456-7890',
    isAdmin: false
  },
  date: '2019-10-28T20:30:54.914Z',
  totalCost: 1149.78,
  totalTax: 10.8
}

我正在尝试从此 JSON 生成架构,但有些地方不正确,因为它会引发错误。现在我正在填充 Mongoose Schema 像

  const newOrder = new Order(req.body);

然后尝试写入 MongoDB 数据库,例如

  newOrder.save()
   .then(() => res.json('Order added!'))
   .catch(err => res.status(400).json(`Error: ${err}`));

保存是抛出被捕获的异常并返回 400。

据我所知,问题似乎是上面显示的“orderList”字段是一个由两个字段组成的数组,一个是对象,一个是数字(分别显示为键“产品”和“数量”)。我在 Mongoose Schema 中描述的对象。问题是本质上是一个“对象数组”似乎没有正确地变成猫鼬模式。除了将 JSON 传递给 Schema 的构造函数之外,我还需要做什么?

【问题讨论】:

  • 错误信息是什么?同时发布您的方案定义
  • 除了绑定保存时抛出的异常没有错误。我注意到应该是一个对象只有一个很长的二进制十六进制数字(我假设它是“_id”,因为我类似于 GUID。我不太擅长标记,所以我无法为您提供我的架构定义。当我尝试它时,它看起来像一个很大的段落,我认为它没有用。

标签: node.js json mongodb mongoose


【解决方案1】:

您可以通过以下两种方式从 JSON 生成猫鼬模式:

1) (困难的方式) 使用递归函数循环您的 JSON 对象并将值替换为其 typeof 值。比如:

req.body.orderList.product = typeof req.body.orderList.product

2) (简单的方法) 使用像 generate-schema 这样的模块,它提供了一个可以从 JSON 生成 Mongoose 模式的函数。通过 npm (npm install generate-schema) 安装它,然后像这样实现:

const generateSchema = require('generate-schema');

let jsonData = req.body;

let MongooseSchema = generateSchema.mongoose(jsonData);

mongooseSchema 现在包含您的架构。运行console.log(mongooseSchema) 返回:

{ orderList: { type: [ 'Mixed' ] },
  user:
   { name: { first: [Object], middle: [Object], last: [Object] },
     address:
      { street1: [Object],
        street2: [Object],
        city: [Object],
        state: [Object],
        zip: [Object] },
     email: { type: 'String' },
     phone: { type: 'String' },
     isAdmin: { type: 'Boolean' } },
  date: { type: 'Date' },
  totalCost: { type: 'Number' },
  totalTax: { type: 'Number' } }

然后您可以执行以下操作:

let mongoose = require('mongoose')
let NewOrder = mongoose.model('Order', MongooseSchema)

let newOrder = new NewOrder(req.body)

newOrder.save()
  .then(() => res.json('Order added!'))
  .catch(err => res.status(400).json(`Error: ${err}`));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 2016-06-24
    • 1970-01-01
    • 2015-04-11
    • 2020-06-17
    相关资源
    最近更新 更多