我已经制作了模型,它具有以下架构:
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的值失败
如何使该功能正常工作?
打印屏幕
答案 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);