gpt4 book ai didi

node.js - 我如何使用带有嵌套外部文档的 MONGODB 聚合框架 - Mongoose 和 NodeJS

转载 作者:可可西里 更新时间:2023-11-01 09:44:37 25 4
gpt4 key购买 nike

我有这些 Mongoose 方案:

//用户模式

exports.User = new Schema({
name: {
type: String,
required: true
},
home: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}]
});

// Release模式

exports.Post = new Schema({
likes: [{
type: Schema.Types.ObjectId,
ref: 'User'
}],
author: {
id: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
name: {
type: String,
required: true
},
shortId: String, // this is User id
},
created: {
type: Date,
default: Date.now,
required: true
}
});

//数据库

中的数据

//用户

{"name" : "Mio Nome",
"home" : [
ObjectId("533af14b994c3647c5c97338")
]}

//发布

 {  "author" : {
"id" : ObjectId("533af14b994c3647c5c97338"),
"name" : "AutoreDelPost"
},
"likes" : [
ObjectId("533af14b994c3647c5c97337"),
ObjectId("533af14b994c3647c5c97339"),
ObjectId("533af14b994c3647c5c97340")
]
}

我想从用户那里获取 home 字段中的帖子,并计算有多少 like 有一个用户

使用此代码,我可以通过populate 显示主页中的所有帖子,但我无法计算点赞数。

req.db.User.find({
_id: req.user._id //req.user is my test user
}, {
home: 1
})
.limit(200)
.populate('home')
.exec(function (err) {
if (!err) {
return res.json(200)
}
return res.json(500, err)
});

//输出

[
{
"_id": "533af0ae994c3647c5c97337",
"name" : "Mio Nome"
"home": [
{
"_id": "533b004e6bcb9105d535597e",
"author": {
"id": "533af14b994c3647c5c97338",
"name": "AutoreDelPost"
},
"likes": [] // i can't see like and i can't count they
}
]

我尝试使用 aggregate 来计数等,但是我看不到帖子被填充但是它们的 _id

req.db.User.aggregate({
$match: {
_id: req.user._id
}
}, {
$project: {
home: 1
}
}, {
$unwind: "$home"
}).exec(function (err, home) {
if (!err) {

return res.json(200, home)
}
return res.json(500, err)
});

//输出

[
{
"_id": "533af0ae994c3647c5c97337",
"home": "533b004e6bcb9105d535597e"
},
{
"_id": "533af0ae994c3647c5c97337",
"home": "533b004e6bcb9105d5355980"
},
{
"_id": "533af0ae994c3647c5c97337",
"home": "533b004f6bcb9105d5355982"
},
{
"_id": "533af0ae994c3647c5c97337",
"home": "533b004f6bcb9105d5355984"
},
{
"_id": "533af0ae994c3647c5c97337",
"home": "533b00506bcb9105d5355986"
}
]

问题:我想从用户那里获取 home 字段中的帖子并计算用户有多少个赞

最佳答案

也许您可以存储更加非规范化的数据并添加一个计数器字段,该字段在每个新的“喜欢”时递增。参见 http://cookbook.mongodb.org/patterns/votes/ .像这样的东西:

update = {'$push': {'voters': user_id}, '$inc': {vote_count: 1}}

关于node.js - 我如何使用带有嵌套外部文档的 MONGODB 聚合框架 - Mongoose 和 NodeJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22793734/

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