I have the following schema defined in two files.
faultreport.js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var FaultReportSchema = new Schema(
{
reporter: {type: String, required: true, max: 128},
comment: [{type: Schema.ObjectId, ref: 'Comment'}],
status: {type: String, default: 'Reported', max: 64},
datetime: {type: Date, required: true},
}
);
module.exports = mongoose.model('FaultReport', FaultReportSchema);
comment.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CommentSchema = new Schema(
{
commenter: {type: String, required: true, max: 128},
comment: {type: String, required: true, max: 1024},
datetime: {type: Date, required: true},
}
);
module.exports = mongoose.model('Comment', CommentSchema);
My idea is that each FaultReport is associated with one Comment on creation, but that further Comments can be added later. I would like to build a express route that can be used to list all of the FaultReports, including the comment string within the associated Comment.
I'm trying to do it like this.
router.get('/list_all', function(req, res, next) {
FaultReport.find(function(err, reports) {
if (err) return console.error(err);
var data = [];
for (var i = 0; i < reports.length; i++) {
console.log(reports[i]);
data.push([reports[i].datetime, reports[i].reporter, reports[i].comment[0].comment]);
}
res.render('list_all', {
title: 'Fault List',
data: data
});
});
});
I am clearly misunderstanding something about the way express/mongoose work, and would very much appreciate any help or advice you can give. What am I doing wrong? What do I need to do?