mongodb - MongoDB 聚合查找不适用于帖子评论
问题描述
我有两个需要在聚合上查找的集合。在帖子需要查找关于列表的评论时,这非常简单。
在这里我定义Content
了模式 -
const ContentSchema = new Schema({
.........
linkName: {
type: String,
},
description: {
type: String,
}
},
{
timestamps: true
});
module.exports = mongoose.model('Content', ContentSchema);
评论架构contentComment
-
const contentCommentSchema = new Schema({
........
content: {
type: Schema.Types.ObjectId,
ref: 'Content'
}
},
{
timestamps: true
});
module.exports = mongoose.model('contentComment', contentCommentSchema);
这是我试图列出Content
带有相应评论的帖子(架构)的查询contentComment
-
const contentPromise = Content.aggregate([
{
$lookup: {
from: 'contentComments',
let: { contentId: '$_id' },
pipeline: [{
$match: {
$expr: {
$eq: [ '$content', '$$contentId' ]
}
}
}],
as: 'nbComments'
}
.......
}
]);
我也试过以下$lookup
-
const contentPromise = Content.aggregate([
{
$lookup: {
from: "contentComments",
localField: "_id",
foreignField: "content",
as: "nbComments"
}
.......
}
];
但每次它返回空数组comments
。
这是MongoDB Compass的两个屏幕截图,用于contents
-
和contentComments
-
nbComments
即使对特定帖子/内容有足够的评论,我也无法弄清楚返回空错误的问题。这是一个屏幕截图 -
解决方案
from 使用复数小写集合名称,就像您在 mongo 终端中使用的那样。
所以你必须使用 contentcomments 而不是 contentComments
您可以使用 contentComment.collection.name
例子:
const AwesomeNameSchema = new Schema({
=
});
module.exports = mongoose.model('AwesomeName', AwesomeNameSchema);
在 mongo 终端
db.AwesomeName.count(); // return 0, not working
db.AwesomeNames.count(); // return 0, not working
db.awesomename.count(); // return 0, not working
db.awesomenames.count(); // return X, working solution
在猫鼬查找中
var AwesomeName = require("./models/AwesomeName.js");
var ParentAwesomeName = require("./models/ParentAwesomeName.js");
// not working
ParentAwesomeName.aggregate([
{
$lookup: {
from: "AwesomeNames",
localField: "_id",
foreignField: "awesome_name",
as: "awesome"
}
.......
}
];
// working
ParentAwesomeName.aggregate([
{
$lookup: {
from: "awesomenames",
localField: "_id",
foreignField: "awesome_name",
as: "awesome"
}
.......
}
];
// working
ParentAwesomeName.aggregate([
{
$lookup: {
from: AwesomeName.collection.name,
localField: "_id",
foreignField: "awesome_name",
as: "awesome"
}
.......
}
];
推荐阅读
- java - 将类变量传递给java中另一个类的方法
- python - Python不会让我绘图,有什么建议吗?
- django - 如何使用 csv 文件通过用户名获取用户电子邮件 ID
- javascript - 谷歌“我感觉很幸运”的 url 有敏感词吗?
- java - 如何将问号添加到 Button android
- mysql - 选择 field1 或 field2 或 field3 与电话号码相同的位置
- perl - 使用 Perl 全局替换电子邮件地址
- django - 有没有办法使用 Django 和 MariaDB 执行不区分重音的查找?
- dynamics-crm - Dynamics CRM 获取帐户详细信息
- java - 数组的乘积超过 Self - Leet Code Time Limit Exceeded