我有以下2个架构
question.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var questionsSchema = new Schema({
nr: Number,
points: Number,
description: String,
isActive: {type: Boolean, required: true, default: true}
});
module.exports = mongoose.model('Question', questionsSchema);
round.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var roundSchema = new Schema({
name: String,
index: Number,
questions: {type: [Schema.Types.ObjectId], ref: 'Question'},
createdOn: {type: Date, required: true, default: Date.now()},
isActive: {type: Boolean, required: true, default: true}
});
module.exports = mongoose.model('Round', roundSchema);
有些数据可以正确填充,但是当我尝试最简单的查询时,它甚至无法工作:
var Round = require('../model/round.server.model.js');
function findAll(req, res) {
Round.find().populate('questions').exec(function (err, results) {
if (err) {
console.log("An error occured when receiving all rounds!", err);
return res.sendStatus(404);
}
console.log(results);
return res.send(results);
});
}
检索所有回合,但问题数组是空的,即使_id本身也消失了
答案 0 :(得分:1)
我认为这是因为你以错误的方式初始化你的人口。我知道你在每一回合中都想要一系列问题。你的错误似乎就在这里。
questions: {type: [Schema.Types.ObjectId], ref: 'Question'}
为了使其正常工作,您应该执行以下操作:
questions: [{type: Schema.Types.ObjectId, ref: 'Question'}]
因为实际上,你正在制作一个type
的数组,这并不意味着什么。