猫鼬的种​​群错误

时间:2017-02-02 05:37:46

标签: mongoose mongoose-populate

我已经通过mongoose定义了PostSchema

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来显示所有评论:

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

1 个答案:

答案 0 :(得分:0)

试试这个你已经参考了一个模型。

 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);
        })
    });