为什么不能 mongo 将我的 ObjectId 推送到预定义的数组中?
Why can't mongo push my ObjectId in a predefined array?
我制作了我的模型,它有这个架构:
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 is not defined".
在尝试投射之前,我遇到了这个错误
为值
转换为 ObjectId 失败
如何让这个功能发挥作用?
打印屏幕
postman call error
Mongoose 的 ObjectId class 在 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);
我制作了我的模型,它有这个架构:
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 is not defined".
在尝试投射之前,我遇到了这个错误 为值
转换为 ObjectId 失败如何让这个功能发挥作用?
打印屏幕
postman call error
Mongoose 的 ObjectId class 在 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);