如何从猫鼬中传递的对象更新一个字段

时间:2019-10-21 20:16:51

标签: mongodb mongoose graphql

如果我有一个看起来像下面的对象

const auth = {
        geohash: args.input.geohash,
        offenses: args.input.offenses,
        online: args.input.online,
        paid: args.input.paid,
        profilePic: args.input.profilePic,
        username: args.input.username,
    }

然后我通过它以更新文档

const update = { _id: mongoose.Types.ObjectId(args._id) }
    const value = await DiscoverUsers.findOneAndUpdate(update, auth, { useFindAndModify: false, new: true })

因此,如果我只想更新用户名,而又不想继续创建用于更新文档中每个字段的变体。 可以说我的突变看起来像这样

 mutation{
  updateDiscoverUsers(_id:"5dab7c198a83f235c89a964a",input:{username:"peter"}){
    username
  }
}

但是这只会更新用户名,但会使其余字段为空,但是我只想找到一种方法来仅更新我在突变中传递的字段,其余字段保持不变。因此我只能更新用户名和profilePic,其余的保持不变。 感谢您的帮助,并在此先感谢

1 个答案:

答案 0 :(得分:0)

您应该使用原子运算符$set仅在需要的位置进行更新,并且只应传递要更新的字段,而不是全部传递,否则所有字段都将被新值更新

like:

const value = await DiscoverUsers.findOneAndUpdate(update, {$set:{username:"pedro"}}, { useFindAndModify: false, new: true })
相关问题