【发布时间】:2021-04-01 16:35:38
【问题描述】:
感谢您抽出时间阅读本文。
我有两个型号positions 和users。我正在尝试将“用户”添加到“招聘人员”数组中,如下面的位置模型中所示。 当我提出 put 请求时,一切顺利,但包含新用户 ID 的修改后的数组无法保存并且给出以下错误。
'在路径“recruiters”中值“[3]”转换为 [ObjectId] 失败'
PositionsModel.js
const positionsSchema = new Schema(
{
title: {
type: String,
required: [true, 'Position title is required'],
},
description: {
type: String
},
recruiters: [{
type: Schema.Types.ObjectId,
ref: "users"
}]
},
{ timestamps: true }
);
usersModel.js
const usersSchema = new Schema(
{
name: {
type: String,
required: [true, "Name must be provided"],
},
email: {
type: String
},
password: {
type: String,
}
},
{ timestamps: true }
);
Controller.js(这里有问题) 我正在发出请求以将招聘人员添加到职位模型中的数组并发送两个参数。 Id(这是职位id)和Recruiter(这是userId)
exports.addRemove = async (req, res, next) => {
try {
const {id, recruiter} = req.params;
//Get Current Position Details
const position = await positionsModel.findById(id)
// Update Position
const newList = position.recruiters.push(recruiter) //this works, It adds the id to array
const newData = {
recruiters: newList
}
//At this point if you console log position.recruiters. You will see the newly added item in the array
const uptPosition = await positionsModel
.findByIdAndUpdate(id, newData, {
new: true,
runValidators: true,
})
.exec(); // this fails with error
if(!uptPosition) {
return res.status(400).json("Position failed to update");
}
//Success Response
return res.status(200).json('Position Updated');
} catch (err) {
console.log({ Error: err.message });
return;
}
当前招聘人员 ID 在数组中的列表
当前招聘人员数组已经有两个 userId。第三个成功添加到newList 变量,但它没有保存在数据库中。您可以在下面看到错误,因为它指向刚刚添加到控制器中的第三个元素
'在路径“recruiters”中值“[3]”转换为 [ObjectId] 失败'
【问题讨论】:
-
在推送之前将
recruiterid 转换为对象id 类型,mongoose.Types.ObjectId(recruiter) -
我试过了,并没有真正帮助。我最终更改了代码来解决这个问题。最好使用 mongoose 的 $Push 和 $Pull 查询来添加/删除 ObjectId 的数组。
标签: node.js mongodb express mongoose mongoose-schema