【发布时间】:2019-06-20 02:36:12
【问题描述】:
项目范围:我正在制作新闻源,例如 Facebook。而且我有一个点赞按钮功能,点击后会为帖子添加点赞。
问题假设我有两个帖子,帖子 A 和帖子 B。
如果我喜欢帖子 A 并再次点赞,那么我的服务器会返回“用户已喜欢帖子”,这行得通。
但是,如果我喜欢帖子 B,那么服务器会返回相同的“用户已经喜欢的帖子”
查询:
Feed.findOne({
owner: req.body.authorId,
$and: [
{
"posts.likes.likeList": {
$elemMatch: { user: req.user._id }
}
},
{ posts: { $elemMatch: { _id: req.body.postId } } }
]
}).then(checkedFeed => {
if (checkedFeed) {
return res.status(400).json({ Error: "User has already liked post" });
}
我认为的问题是当用户喜欢帖子 B 而帖子 A 被点赞时,$and 运算符将req.user._id 与第一个索引中帖子 A 的 posts.likes.likeList 匹配$and 数组。然后,它匹配posts 的_id 在$and 数组的第二个索引中。然后将整个提要作为匹配项返回。
那么,如果我在这方面是正确的,我该如何编写一个查询来匹配 post id($and 数组的第二个索引)与 post.likes.likeList 用户列表?
架构
{
owner: {
type: Schema.Types.ObjectId,
ref: "userType"
},
posts: [
{
likes: {
totalLikes: { type: Number, default: 0 },
likeList: [
{
user: { type: Schema.Types.ObjectId, ref: "User" },
avatar: { type: String },
name: { type: String },
date: {
type: Date,
default: Date.now
}
}
]
}
});
测试数据*
{
//POST B <-------
"_id" : ObjectId("5d0a61bc5b835b2428289c1b"),
"owner" : ObjectId("5c9bf6eb1da18b038ca660b8"),
"posts" : [
{
"likes" : {
"totalLikes" : 0,
"likeList" : []
},
"_id" : ObjectId("5d0a61bc5b835b2428289c1c"),
"postBody" : "Test text only",
"author" : {
"userType" : "User",
"user" : ObjectId("5c9bf6eb1da18b038ca660b8"),
"name" : "Amari DeFrance",
"avatar" : "https://stemuli.blob.core.windows.net/stemuli/profile-picture-e1367a7a-41c2-4ab4-9cb5-621d2008260f.jpg"
}
},
{
//Post A <------
"likes" : {
"totalLikes" : 1,
"likeList" : [
{
"_id" : ObjectId("5d0a66efbac13b4ff8b3b1c8"),
"user" : ObjectId("5c9bf6eb1da18b038ca660b8"),
"avatar" : "https://stemuli.blob.core.windows.net/stemuli/profile-picture-e1367a7a-41c2-4ab4-9cb5-621d2008260f.jpg",
"name" : "Amari DeFrance",
"date" : ISODate("2019-06-19T16:46:39.177Z")
}
]
},
"postBody" : "Test photo",
"author" : {
"userType" : "User",
"user" : ObjectId("5c9bf6eb1da18b038ca660b8"),
"name" : "Amari DeFrance",
"avatar" : "https://stemuli.blob.core.windows.net/stemuli/profile-picture-e1367a7a-41c2-4ab4-9cb5-621d2008260f.jpg"
},
"date" : ISODate("2019-06-19T16:25:26.123Z")
}
],
"__v" : 3
}
每个建议答案的新查询
Feed.aggregate([
{
$match: {
$expr: {
$and: [
{
$eq: ["$owner", req.body.authorId]
},
{
$anyElementTrue: {
$map: {
input: "$posts",
in: {
$and: [
{
$eq: ["$$this._id", req.body.postId]
},
{
$anyElementTrue: {
$map: {
input: "$$this.likes.likeList",
as: "like",
in: {
$eq: ["$$like.user", req.user._id]
}
}
}
}
]
}
}
}
}
]
}
}
}
]).then(checkedFeed => {
if (checkedFeed.length !== 0) {
return res.status(400).json({ Error: "User has already liked post" });
}
MongoDB query test with post B having liked post from the user
【问题讨论】:
标签: mongodb mongodb-query