【发布时间】:2020-07-13 09:53:57
【问题描述】:
我设置了这个突变:
followUser: {
type: UserType,
args: {
_id: { type: GraphQLString },
firebaseUid: { type: GraphQLString },
following: { type: new GraphQLList(GraphQLString)},
},
resolve(parentValue, { firebaseUid, _id, following}) {
const update = {
$set: { "following": [firebaseUid] },
$push: { "following": { firebaseUid } }
}
return UserSchema.findOneAndUpdate(
{ _id },
update,
{new: true, upsert: true}
)
}
},
我正在尝试将新的关注者添加到我的 graphql 用户的收藏中。我的用户模型:
const UserSchema = new Schema(
{
firebaseUid: String,
following: [{ type: Schema.Types.ObjectId, ref: 'User' }],
followers: [{ type: Schema.Types.ObjectId, ref: 'User' }],
},
{ timestamps: true }
);
module.exports = mongoose.model("User", UserSchema);
所以一开始,用户没有任何关注者,所以它还没有那个字段。当用户将某人添加到他们的朋友列表中时,该字段将出现在 mongodb 中。现在我收到了这个错误:
"message": "'$set' is empty. You must specify a field like so: {$set: {<field>: ...}}",
我不确定我是否正确地执行$set。
用户类型
const UserType = new GraphQLObjectType({
name: "User",
fields: () => ({
_id: { type: GraphQLString },
firebaseUid: { type: GraphQLString },
following: { type: new GraphQLList(GraphQLString) },
followers: { type: new GraphQLList(GraphQLString) },
...
})
});
编辑:
当前 mongodb 数据收集:
_id: ObjectId("5e5c24111c9d4400006d0001")
name: "Mr. Smith"
username: "mrsmith"
运行更新后
_id: ObjectId("5e5c24111c9d4400006d0001")
name: "Mr. Smith"
username: "mrsmith"
following: ["fdsaduybfeaf323dfa"] // <-- this gets added
【问题讨论】:
-
您正在设置并推送到同一个字段。这是故意的吗?
-
@als 我的理解是,由于数据库中还没有以下内容,我想我必须先“设置”它,然后“推送”该字段的新更改?我理解错了吗?我不确定这是否是我应该做的
-
如果您使用
$set: { "following": [firebaseUid] },那么following应该是一个包含firebaseUid作为其第一个也是唯一一个条目的数组。 -
@als 我更新了我的帖子以说明当前数据,并在更新后说明了我想要实现的目标。我以为我需要
$set: { "following": [firebaseUid] },因为它还没有数组字段,然后想根据$push推送一个ID -
如果你还没有数组,你应该只使用
$set而不使用$push,因为如果你设置了数组[firebaseUid],那么创建的数组不会是空的,而是什么您提供给$set操作员