Add/Remove 用户访问 ObjectId 数组失败

Add/Remove users to an array of ObjectId Fails

感谢您抽出时间阅读本文。 我有两个模型 positionsusers。我正在尝试将 'users' 添加到 'Recruiters' 的数组中,如下面的位置模型所示。 当我发出放置请求时,一切顺利,但我修改后的数组包括新的userids 无法保存并给出以下错误。

'Cast to [ObjectId] failed for value "[3]" at path "recruiters"'

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 列表

Current Recruiter Array 已有两个 userId。第三个成功添加到 newList 变量,但它没有保存在数据库中。您可以看到下面的错误,因为它指向刚刚添加到控制器中的第三个元素

'Cast to [ObjectId] failed for value "[3]" at path "recruiters"'

The push() method adds one or more elements to the end of an array and returns the new length of the array.

你做到了:

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

那么 newList 将是招聘人员数组的新长度(在你的例子中是 3)。您可以通过将代码更改为:

来解决此问题
position.recruiters.push(recruiter);
position.markModified('recruiters'); // mark recruiters as having pending change
position.save();