如何解决对mongodb中的不可变字段执行更新

时间:2019-10-19 19:01:52

标签: mongodb mongoose graphql

我正在写一个变异来更新数据库中的集合

updateDiscoverUsers(_id:ID!,input: UpdateDiscoverUsersInput!): DiscoverUsers

下面的resolver函数是处理该突变的函数

updateDiscoverUsers: async (args) => {
    const auth = new DiscoverUsers({
        geohash: args.input.geohash,
        offenses: args.input.offenses,
        online: args.input.online,
        paid: args.input.paid,
        profilePic: args.input.profilePic,
        username: args.input.username,
        creator: "5dab348c8890af1b8c25b22e"
    })

    const value = await DiscoverUsers.findByIdAndUpdate(args._id, { $set: auth }, { useFindAndModify: false, new: true }) 
    if (!value) {
        throw new Error('User doesnt exist')
    }
    return transformUser(value)
}

下面是要返回的值的类型

    type DiscoverUsers{
    _id:ID!
    geohash: String!
    offenses:Int
    online: Int
    paid: Boolean
    profilePic: String
    username: String
    creator: Auth!
}

下面也是输入类型,其中包含用于更新集合中任何字段的值

    input UpdateDiscoverUsersInput{
    geohash: String
    offenses:Int
    online: Int
    paid: Boolean
    profilePic: String
    username: String
}

但是当我尝试在graphiql中运行突变时,如下所示

 mutation {
  updateDiscoverUsers(_id:"5dab7c198a83f235c89a964a",input: {geohash:"dudknudnud", username: "Wacha"}){
    username
  }
}

我收到一个显示在我的graphiql中的错误

  

{     “错误”:[       {         “ message”:“在路径'_id'上执行更新将修改不可变字段'_id'”,         “位置”:[           {             “行”:2             “栏”:3           }         ],         “路径”:[           “ updateDiscoverUsers”         ]       }     ],     “数据”:{       “ updateDiscoverUsers”:null     }   }

我试图检查问题似乎在哪里,已经在线检查并且没有类似的问题。任何帮助都将受到欢迎,并预先感谢您

1 个答案:

答案 0 :(得分:0)

Please use following code

      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,
      creator: "5dab348c8890af1b8c25b22e"
    };
    const updateCond={_id:mongoose.Types.ObjectId(args._id)}
    const value = await DiscoverUsers.findOneAndUpdate(updateCond, auth, { new: true });