为什么mongo无法将我的ObjectId推送到预定义的数组中?

时间:2018-12-11 11:42:51

标签: mongodb mongoose mongodb4.0

我已经制作了模型,它具有以下架构:

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

但我不断收到此错误: “错误”:“未定义ObjectId”。

在尝试投射之前,出现了此错误 转换为ObjectId的值失败

如何使该功能正常工作?

打印屏幕

postman call error

1 个答案:

答案 0 :(得分:1)

猫鼬的ObjectId类在Mongoose.Schema.Types.ObjectId上定义

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

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

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

global.Mongoose = require('mongoose')

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

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