-1

我制作了我的模型,它有这个模式:

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”。

在我尝试强制转换之前,我收到了这个错误 Cast to ObjectId failed for value

我怎样才能让这个功能工作?

打印屏幕

邮递员呼叫错误

4

1 回答 1

1

mongoose 的 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);
于 2018-12-11T13:07:53.190 回答