猫鼬阵列人口

时间:2017-01-18 11:30:47

标签: node.js mongodb mongoose-populate

我已经在mongoose的帮助下创建了一个数据库,现在我正在尝试使用它的引用来填充文档。填充单个文档引用可以正常工作,而填充数组则不行。

给我带来麻烦的模型如下:

任务

var taskSchema = new Schema({
    _client: { type: Schema.Types.ObjectId, ref: 'Client', required: true },
    link: { type: String, required: true },
    reqDate: { type: Date, default: Date.now },
    startDate: { type: Date },
    extId: { type: String, required: true },
    results: [{ type: Schema.Types.ObjectId, ref: 'Result' }]
});
var Task = mongoose.model('Task', taskSchema);

结果

var resultSchema = new Schema({
    _task: { type: Schema.Types.ObjectId, ref: 'Task', required: true },
    _module: { type: Schema.Types.ObjectId, ref: 'Module', required: true },
    finishDate: { type: Date, required: true },
    result: { type: Object, required: true }
});
var Result = mongoose.model('Result', resultSchema);

我使用以下代码将结果添加到数据库中:

let taskPromise = Task.findById(req.params.taskId).exec();
let modulePromise = Module.findOne({ name: req.body.module }).exec();

// Wait for promises to finish
Promise.all([taskPromise, modulePromise])
    .then(values => {
        if (values[1]) {
            // Create new result and add to database
            let result = new Result({
                _task: values[0],
                _module: values[1],
                finishDate: Date.now(),
                result: req.body.result
            });
            result.save();

            res.json({ result: 'success' });
        } else {
            // If findOne does not find a result, it resolves the promise instead of rejecting it
            // Therefore Promise.all is successful and we have to check for errors like this
            res.json({ error: 'The module is invalid' });
        }
        // findById on the other hand rejects a promise when it does not find a result
        // That's why we are catching the error here.
    }).catch(err => res.json({ error: 'The task is invalid' }));

结果通过API调用添加,请求正在预先验证。

要填充,我使用以下代码:

Task.findById('587f48ba009932409cf51626')
        .populate('results _client').exec(function(err, task) {
            res.json(task);
        });

不要介意没有错误处理,这只是出于调试原因,因为ID是硬编码的

_client的人口可以正常工作,而results仍然是一个空数组,即使数据库填充了此任务的结果。

我一直关注documentation,并且没有看到我的代码有任何不同,所以我不知道我可能做错了什么。

对此的想法非常感谢

E /

我使用

进行了测试
Result.find({_task: task}, function(err, result) {
    console.dir(result);
})

获取此任务的结果非常正常,并且可以提供我需要的所有文档。我想这会引起参考问题,我仍然无法找到任何错误。

1 个答案:

答案 0 :(得分:-1)

Task.findById('587f48ba009932409cf51626')
        .populate('_client')
        .populate('results')
        .exec(function(err, task) {
            res.json(task);
        })