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