gpt4 book ai didi

javascript - 如何计算 ObjectId 数组中 ObjectId 的出现次数并将结果附加到要返回的每个文档?

转载 作者:行者123 更新时间:2023-11-30 20:57:00 28 4
gpt4 key购买 nike

我有一个标签模式:

const TagSchema = new Schema({
label: {type: String, unique: true, minlength: 2},
updatedAt: {type: Date, default: null},
createdAt: {type: Date, default: new Date(), required: true},
createdBy: {type: mongoose.Schema.Types.ObjectId, ref: 'Account', default: null}
});

const Tag = mongoose.model('Tag', TagSchema);

然后我有一个 Page 架构:

const PageSchema = new Schema({
tags: {type: [{type: mongoose.Schema.Types.ObjectId, ref: 'Tag'}], default: [], maxlength: 5}
});

const Page = mongoose.model('Page', PageSchema);

如您所见,它在其 tags 数组中包含一个 Tag 引用。

现在我需要做的是当我通过/tags获取所有标签时,我还需要统计每个标签在所有Page中被使用的次数.

因此,如果一个标签在所有Page中被使用了2次,它应该设置一个.occurrences返回标签上的属性。例如,这将是来自 /tags 的响应:

[
{_id: '192398dsf7asdsdds8f7d', label: 'tag 1', updatedAt: '20170102', createdAt: '20170101', createdBy: '01238198dsad8s7d78ad7', occurrences: 2},
{_id: '19239asdasd8dsf7ds8f7d', label: 'tag 2', updatedAt: '20170102', createdAt: '20170101', createdBy: '01238198dsad8s7d78ad7', occurrences: 1},
{_id: '192398dsf7zxccxads8f7d', label: 'tag 1', updatedAt: '20170102', createdAt: '20170101', createdBy: '01238198dsad8s7d78ad7', occurrences: 5},
]

我本以为我可以在 Mongoose pre('find') 钩子(Hook)中很容易地实现这一点,如下所示:

TagSchema.pre('find', function() {

Page.count({tags: this._id}, (err, total) => {
this.occurrences = total;
});
});

但是,这里有两个问题:

  • Page.count 抛出一个错误,说它不是一个函数,我不明白为什么,因为我在其他地方使用它非常好。 Page 已正确导入。建议您不能在钩子(Hook)或类似的东西中使用 count

  • this 不是 Tag 文档。

所以我想我处理这个问题的方式是完全错误的。

由于我是 MongoDB 的新手,也许有人可以为我提供更好、更有效的解决方案?

最佳答案

db.Page.aggregate([ 
{
$unwind:"$tags"
},
{
$group:{
_id:"$tags",
occurrences:{$sum:1}
}
},
{
$lookup:{ //get data for each tag
from:"tags",
localField:"_id",
foreignField:"_id",
as:"tagsData"
}
},
{
$project:{
tagData:{$arrayElemAt: [ "$tagsData", 0 ]},
occurrences:1
}
}
{
$addFields:{
"tagData._id":"$_id",
"tagData.occurrences":"$occurrences"
}
},
{
$replaceRoot: { newRoot: "$tagData" }
}
])

关于javascript - 如何计算 ObjectId 数组中 ObjectId 的出现次数并将结果附加到要返回的每个文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47554648/

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