【问题标题】:Add/Remove users to an array of ObjectId Fails将用户添加/删除到 ObjectId 数组失败
【发布时间】:2021-04-01 16:35:38
【问题描述】:

感谢您抽出时间阅读本文。 我有两个型号positionsusers。我正在尝试将“用户”添加到“招聘人员”数组中,如下面的位置模型中所示。 当我提出 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] 失败'

【问题讨论】:

  • 在推送之前将recruiter id 转换为对象id 类型,mongoose.Types.ObjectId(recruiter)
  • 我试过了,并没有真正帮助。我最终更改了代码来解决这个问题。最好使用 mongoose 的 $Push 和 $Pull 查询来添加/删除 ObjectId 的数组。

标签: node.js mongodb express mongoose mongoose-schema


【解决方案1】:

push() 方法将一个或多个元素添加到数组的末尾,并返回数组的新长度。

你做到了:

const newList = position.recruiters.push(recruiter);

然后newList 将是招聘人员数组的新长度(在您的情况下为 3)。您可以通过将代码更改为:

position.recruiters.push(recruiter);
position.markModified('recruiters'); // mark recruiters as having pending change
position.save();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 2016-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多