我正在使用MongoDB、Mongoose和Node.js和Express.网站上的js.我研究了教程Point、MongoDB文档、堆栈溢出和Mongoosejs.com,但找不到这个问题的答案.我将此作为我的文档模型之一:

const mongoose = require('mongoose')
const Schema = mongoose.Schema;

const QuestionSchema = new Schema ({
    userid: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: false
    },
    title: String,
    keyword1: String,
    keyword2: String,
    keyword3: String,
    body: String,
    upvotes: {
        type: Number,
        default: 0
    },
    datePosted: {
        type: Date,
        default: new Date()
    },
    answers: [{
        respondentID: mongoose.Schema.Types.ObjectId,
        respondent: String,
        text: String,
        date: Date,
        upvotes: Number
    }]
});

const Question = mongoose.model('Question', QuestionSchema);

module.exports = Question

在其中一个页面上,我想显示所有的"答案",这是嵌入在上面的"问题"模型中的一系列子文档.这是我的express .试图"提取"答案数组的js控制器(console.log条目正在try 不同的方法来获取答案数组):

const { typeOf } = require('mathjs');
const Question = require('../models/Question')

module.exports = async (req,res) =>{
    console.log("You are inside displayAnswers controller!")
    const thisQuestionID = req.body.questionID;
    console.log("Display answers ID: " + thisQuestionID);
    
    if (thisQuestionID == 0) {
        console.log("Inside thisQuestionID == 0")
        res.redirect("index");
    } else {    
        const answers = await Question.find({"_id" : thisQuestionID}, {"answers": 2});   
        console.log("Answers: " + answers)
        console.log("Answer[0]: " + answers.answers[0])
        console.log(typeOf(answers.answers[0]))
        console.log("Answers Length: " + answers[0].length)
        console.log("Answers Size: " + answers[0].size)
        res.render('displayAnswers', {
            thisQuestionID,
            answers
        })
    }
}

The problem I have is that the answers variable shows up like this in the console: enter image description here

但我似乎无法访问子文档.我想我可以说answers[0]或answers[#],其中#是1,或2,或子文档的索引是什么,等等,但除answers[0]之外的任何内容都是未定义的和answers.长度始终显示为"1".我似乎找不到允许我在子文档数组中迭代每个单独文档的语法.我还判断了控制台.log(typeOf(answers))并确认它是一个数组,因此我不明白为什么我不能通过说出answers[0]和answers1等来访问数组中的每个子文档.就好像Mongoose/Javascript认为answers是一个长度为1的数组,其中只有一个元素,即使其中有两个子文档用逗号分隔.

有什么 idea 吗?

推荐答案

我认为您只是对返回类型感到困惑,可能是因为命名不正确:

const answers = await Question.find({{"_id" : thisQuestionID})

该语法返回一个"问题"数组,只是因为您仅投影特定的子字段(在本例中为"答案")并不会改变这一点.

这意味着answers看起来像这样:

[
  { answers: Answer[] }
]

您应该这样做:(我们使用findOne而不是find来简化代码)

const questionBody = await Question.findOne({"_id" : thisQuestionID}, {"answers": 2});
const answers = questionBody.answers

甚至清洁剂只需使用distinct

const answers = await Question.distinct("answers", {"_id" : thisQuestionID});

两者都会给你一系列你期望的答案.

Node.js相关问答推荐

需要关于基于角色授权的设计建议

容器端口是容器内 node 应用程序的端口吗?

如何在Firebase Cloud Function v2计划函数中设置代码中的时区?

如何在ejs模板中使用循环显示多个结果?

如何将Node.js与Nuxt.js一起使用?

无法从MongoDB文档中保存的对象数组中获取对象的属性

在 puppeteer 中从 pdf 中删除 about:blank 和 date-time

如何在 JavaScript 中显示多维数组中使用的一维数组的变量名?

如何在 node /快速服务器上配置 mongoDB

如何通过node下载zip并直接解压zip?

Angular Build 生产返回致命的 javascript 无效大小错误

处理 UTC 日期和future

如何删除mongodb中嵌套数组中所有出现的数组元素

try 在 Heroku 中部署 PRN 应用程序并获得 404

是Electron 的密码和登录凭据的安全存储吗?

带有 node.js 和 express 的基本网络服务器,用于提供 html 文件和assets资源

`npm install` 以Killed结尾

异步函数 - 等待不等待promise

如何在 Node.js 中使用 chmod

如何在 node 中转义 shell 命令的字符串?