mongoose 无法在findOneAndUpdate操作中省略_id字段

rwqw0loc  于 2024-01-08  发布在  Go
关注(0)|答案(1)|浏览(159)

我有一个更新mongoDB文档的函数。在对发送的数据进行操作后,我使用mongoose的findOneAndUpdate函数更新想要的文档。因为我将使用保存的数据,所以我设置了new:true,并使用名为userReturnFormat的对象作为投影来检索必要的字段。代码示例:

const userReturnFormat = {
    email: 1,
    name: 1,
    surname: 1,
    _id: 0
}

const updatedUser = (await UserModel.findOneAndUpdate(
            { registerId: params.user.registerId },
            { $set: data },
            { new: true, projection: userReturnFormat }
        )) as User

字符串
正如你在userReturnFormat对象中看到的,_id字段被标记为false。当我使用{_id:0}作为投影时,它成功地省略了_id字段。我尝试过在更新操作中直接写入投影,但当我将任何属性标记为true时,它仍然返回_id字段。我可以使用删除操作数删除_id字段更新文档后,但我不想使用这个,因为投影应该能够用于此目的。
{_id: 0 }作为投影:

const updatedUser = (await UserModel.findOneAndUpdate(
            { registerId: params.user.registerId },
            { $set: data },
            { new: true, projection: { _id: 0 } }
        )) as User


结果:

{
  email: ‘[email protected]’,
  password: ‘HASHED_PASSWORD’,
  name: ‘JOHN’,
  surname: ‘DOE’,
  type: ‘example’,
  createdAt: 2024-01-03T12:57:20.972Z,
  updatedAt: 2024-01-04T07:30:27.153Z
}


使用delete操作数:

const updatedUser = (
            await UserModel.findOneAndUpdate({ registerId: params.user.registerId }, { $set: data }, { new: true, projection: userReturnFormat })
        )?._doc

delete updatedUser._id


结果:

{
  email: ‘[email protected]’,
  name: ‘JOHN’,
  surname: ‘DOE’,
}

uidvcgyl

uidvcgyl1#

使用select

await UserModel.findOneAndUpdate(
   { registerId: params.user.registerId },
   { $set: data },
   { new: true }
).select(userReturnFormat).exec();

字符串

相关问题