【问题标题】:Get count number from mongoDB从 mongoDB 获取计数
【发布时间】:2020-05-17 14:00:57
【问题描述】:

我正在使用 mango 和 express 创建问答网站。所以问答有两种模式。

我的问答模式是这样的,

const questionSchema = mongoose.Schema({
_id : mongoose.Schema.Types.ObjectId,
user: { type:mongoose.Schema.Types.ObjectId, ref: 'User', required: true},
title: {type: String , required:true},
question: {type: String , required:true},
tags: {type: Array , required: true},
time : { type : Date, default: Date.now },
vote: {type: Number, default: 0},
views: {type: Number, default: 0}     });


const answerSchema = mongoose.Schema({
_id : mongoose.Schema.Types.ObjectId,
user: { type:mongoose.Schema.Types.ObjectId, ref: 'User', required: true},
question:{ type:mongoose.Schema.Types.ObjectId, ref: 'Question', required: true},
comment: [{type: mongoose.Schema.Types.ObjectId, ref: 'Comment', default: null }],
answer: {type: String, required: true},
vote: {type: Number , default: 0},
time : { type : Date, default: Date.now }   });

这里有很多与一个问题相关的答案。我的主页可以预览所有问题。如何获得与每个问题相关的答案的计数?

【问题讨论】:

  • 您想用问题名称查询question 集合并获取所有答案计数吗?
  • 是的。我想获取每个问题的问答数
  • 你试过我的答案了吗?
  • 是的,但计数总是为 0。我认为 localField 和 foreignField 名称与我的架构相关的问题。
  • 谢谢@whoami 。我从="Answer" 更改为 from="answers" 后就可以了。其作品。

标签: mongodb express mongoose mongoose-schema


【解决方案1】:

由于您的 questionSchemaAnswers 集合没有任何直接关系(例如不存储 Answers 参考),请尝试以下操作:

查询:

db.Question.aggregate([
    {
        $lookup:
        {
            from: "Answer",
            localField: "_id",
            foreignField: "question",
            as: "answers"
        }
    }, 
    /** In case if you need all details of question replace 'project' with 'addFields' & remove 'question: 1' */
    { $project: { question: 1, count: { $size: '$answers' } } } 
])

测试: MongoDB-Playground

【讨论】:

    猜你喜欢
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多