javascript - 简单的 Mongoose 填充似乎不起作用

标签 javascript mongodb mongoose

我有以下 2 个架构

问题.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);

圆形.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 本身也消失了

最佳答案

我认为这是因为你以错误的方式初始化了你的人口。我知道您希望在每一轮中提出一系列问题。您的错误似乎就在这里。

 questions: {type: [Schema.Types.ObjectId], ref: 'Question'}

您应该执行以下操作才能使其正常工作:

 questions: [{type: Schema.Types.ObjectId, ref: 'Question'}]

因为实际上,您正在创建一个 type 数组,但这没有任何意义。

关于javascript - 简单的 Mongoose 填充似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28566545/

相关文章:

javascript - Mongoose.js : Find users, 然后检查用户的值

mongodb - 展开和匹配后的组数组

javascript - 如何向 Mapbox 传单 map 添加多个过滤器

javascript - 如何让 2 个 YouTube 视频一个接一个地自动播放?

c# - 如何在 C# 中为以下 MongoDB 查询场景编写搜索查询

javascript - 如何在 MeteorJS 中更新 MongoDB 集合上的子文档数组

json - 将 ObjectID 与 jwt.sign() 和 verify() 结合使用

javascript - 在 jQuery 中使用 .hide() 和 .show()

javascript - D3 v4 中的 Nest() 函数生成带有 $ 符号的键

javascript - 如何连接到 mongoDB 并测试 drop 收集?