【问题标题】:Why can't mongo push my ObjectId in a predefined array?为什么 mongo 不能将我的 ObjectId 推送到预定义的数组中?
【发布时间】:2018-12-11 21:07:53
【问题描述】:

我已经制作了我的模型,它有这个架构:

const CompanySchema = new Schema({
    companyName: {
      type: String,
      required: [true,'the name of the companies working on the game are missing.']
    },
    companyAge: {
      type: Number,
      required: [true,'the age of the company is missing.']
    },
    companyDeveloper:[{
      type: Schema.Types.ObjectId,
      ref: "developer"
    }]
  });

我正在尝试将一个元素推入 companyDeveloper 数组,如下所示:

  addDev(req,res,next){
    const companyId = req.params.id;
    const companyDeveloper = ObjectId.fromString(req.body.companyDeveloper);
    Company.findById({_id: companyId})
    .then((company) => company.companyDeveloper.push({companyDeveloper}))
    .then(company => res.send(company))
    .catch(next);
  }

但我不断收到此错误: "error": "ObjectId 未定义"。

在我尝试投射它之前,我收到了这个错误 转换为 ObjectId 的值失败

我怎样才能让这个功能发挥作用?

打印屏幕

postman call error

【问题讨论】:

    标签: mongodb mongoose mongodb4.0


    【解决方案1】:

    mongoose 的 ObjectId 类在 Mongoose.Schema.Types.ObjectId 上定义

    您可以在定义addDev的文件中要求它

    const ObjectId = require('mongoose').Schema.Types.ObjectId
    

    或将 mongoose 加载到您初始化节点代码的全局中,以便您可以在任何文件中访问它:

    global.Mongoose = require('mongoose')
    

    然后在你的方法中使用它:

    const companyDeveloper = Mongoose.Schema.Types.ObjectId.fromString(req.body.companyDeveloper);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-28
      • 2015-03-19
      • 2019-02-12
      • 1970-01-01
      • 2021-11-05
      • 2023-04-06
      • 2012-09-03
      • 2022-12-07
      相关资源
      最近更新 更多