gpt4 book ai didi

arrays - MongoDb嵌套数组查询以下关系

转载 作者:可可西里 更新时间:2023-11-01 09:52:20 26 4
gpt4 key购买 nike

假设我有一个用户模式:

UserSchema = new Schema({
name: {
first: { type: String, trim: true },
last: { type: String, trim: true }
},
username: { type: String, trim: true, required: true },
email: { type: String, trim: true, required: true },
hashed_password: { type: String, trim: true, required: true },
profile_image: { type: String, trim: true, default: 'default' },
join_date: { type: Date, required:true },
userFollows: [ {
status : { type: String, enum: [
'following',
'followed_by'
]},
added : { type: Date, required:true },
user : { type: Schema.ObjectId, ref: 'User'}
} ]
})

我需要将新的 userFollows 推送到此模式,但我还需要检查用户当前是否关注该用户(重复条目),但我不确定如何执行此查询

我正在尝试使用的当前查询是:

User
.findOne(
{ username: req.user.username },
{ "userFollows.user": { $not: req.body.userID } }
)
.exec(function (err, currentUser) {

})

但它不起作用。

我想避免在执行查询和手动检查后循环遍历 currentUser.userFollows 数组

我需要推送的最终 userFollows 对象如下所示:

{
_id: ObjectId("53073acd9256e81e4d7b5d8e"),
status: "followed_by",
added: ISODate("2014-02-21T11:38:53.828Z"),
user: ObjectId("51c6ec9fedc1230700000007")
}

最佳答案

有两种方法可以进行此更新(在 shell 语法中):

db.users.update( 
{ "username": req.user.username },
{ $addToSet : { userFollows : { _id: ObjectId("53073acd9256e81e4d7b5d8e"),
status: "followed_by",
added: ISODate("2014-02-21T11:38:53.828Z"),
user: ObjectId("51c6ec9fedc1230700000007")
}
}
}
)

表示,对于这个用户,将这个对象添加到 userFollows 数组(除非它已经存在)。

另一种方法是:

db.users.update( 
{ "username": req.user.username, "userFollows.user": { $ne: req.body.userID } },
{ $push : { userFollows : { _id: ObjectId("53073acd9256e81e4d7b5d8e"),
status: "followed_by",
added: ISODate("2014-02-21T11:38:53.828Z"),
user: ObjectId("51c6ec9fedc1230700000007")
}
}
}
)

它说:对于这个还没有这个关注者的用户,$push 这个对象。

显然您会填写适当的字段 - 我只是从您的问题中剪切并粘贴一些示例值以显示完整格式。

关于arrays - MongoDb嵌套数组查询以下关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21934589/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com