【问题标题】:A population error of mongoose猫鼬的种​​群错误
【发布时间】:2017-02-02 17:21:05
【问题描述】:

我已经定义了一个 PostSchema by mongoose:

var PostSchema = new mongoose.Schema({
  comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
  editor: { post: { type: mongoose.Schema.Types.ObjectId, ref: 'Post' }, codes: [{ type:mongoose.Schema.Types.ObjectId, ref: 'Code' }] }
});

因为这段代码,我可以使用http://localhost:3000/#/posts/5879fc91b7a56002237f30f5 来显示所有的cmets:

router.get('/posts/:post', function (req, res, next) {
    req.post.populate('comments', function (err, post) {
        if (err) { return next(err); }

        res.json(post);
    });
});

现在,我想用http://localhost:3000/#/posts/5879fc91b7a56002237f30f5/editor来获取editor的所有内容,包括codes里面的内容。但是下面的代码打印出["5892bbc68abcc926f7f1dd93","5892bbdf8abcc926f7f1dd94","5892bc178abcc926f7f1dd95","5892bc1b8abcc926f7f1dd96"]

router.get('/posts/:post/editor', function (req, res, next) {
    req.post.editor.populate('codes', function (err, editor) {
        if (err) { return next(err); }
        console.log(JSON.stringify(editor.codes));
        res.json(editor);
    })
});

有谁知道如何正确填充codes

【问题讨论】:

    标签: mongoose mongoose-populate


    【解决方案1】:

    试试这个你有参考一个模型。

     router.get('/posts/:post/editor', function (req, res, next) {
            req.post.populate({path:'editor.codes',model:'Code'}, function (err, editor) {
                if (err) { return next(err); }
                console.log(JSON.stringify(editor.codes));
                res.json(editor);
            })
        });
    

    【讨论】:

    • 我试过req.post.editor.populate({path:'codes',model:'Code'}, function (err, editor)...,它仍然只是打印ID...
    • 编辑了答案现在试试。我不明白你为什么要写 post.editor ?
    • 我现在无法测试它。简单说一下:如果我们使用req.post.populate(,我们应该使用function (err, editor)还是function (err, post)
    • 它不会影响两者都是同一事物编辑器或发布两者都是包含来自该查询的结果的参数。只需尝试上面的代码,它应该可以工作。
    猜你喜欢
    • 2016-07-31
    • 2019-09-13
    • 2017-06-02
    • 2016-07-11
    • 2018-02-10
    • 2013-11-27
    • 2016-12-17
    • 2018-09-13
    • 2016-07-02
    相关资源
    最近更新 更多