【问题标题】:Submit a model in Mongoose that contains an array with ObjectID's在 Mongoose 中提交一个模型,其中包含一个带有 ObjectID 的数组
【发布时间】:2020-04-22 12:46:52
【问题描述】:

我有一个名为company 的对象,里面有name(String)locations(Array) 在位置内部,我想要一个名为name 的密钥,用户将生成该密钥,第二个密钥是使用ObjectID 生成的。 不幸的是,我无法让它按预期工作。

Example from Postman。请注意,这些位置没有得到_id

出了什么问题?

我的模型

const mongoose = require('mongoose')

const companySchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  name: String,
  locations: [
    {
      _id: mongoose.Schema.Types.ObjectId,
      name: String
    }
  ]
})

module.exports = mongoose.model('Company', companySchema)

我的控制器

  createCompany: (req, res) => {
    const { name, locations } = req.body

    const company = new Company({
      _id: new mongoose.Types.ObjectId(),
      name: name,
      locations: locations
    })

    company
      .save()
      .then(() => {
        res.status(200).json({
          company
        })
      })
      .catch(error => {
        res.status(500).json({
          error
        })
      })
  },

【问题讨论】:

  • 请使用该架构 const companySchema = mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, name: String, locations: [ { name: String } ] })
  • 为什么?我想为每个位置设置 _id。据我所知,我需要它成为架构的一部分..
  • 因为在collection中自动定义了id

标签: node.js reactjs mongodb mongoose


【解决方案1】:

Mongoose 将为文档本身的顶层和嵌套数组创建 _id,这是默认行为。

因此,应该只使用您想要的字段来定义架构。

const companySchema = new mongoose.Schema({
  name: String,
  locations: [
    {
      name: String
    }
  ]
});
module.exports = mongoose.model("Company", companySchema);

const locationSchema = new mongoose.Schema({
  name: String
});
const companySchema = new mongoose.Schema({
  name: String,
  locations: [locationSchema]
});
module.exports = mongoose.model("Company", companySchema);

随后您也不需要从 Model 对象创建 _id

const company = new Company({
  name: name,
  locations: locations
});
company
  .save()
  .then(() => {})
  .catch(e => {});

【讨论】:

    猜你喜欢
    • 2016-06-13
    • 2020-08-23
    • 2020-01-11
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多