猫鼬的人口错误

A population error of mongoose

我已经通过 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 吗?

试试这个你有参考模型。

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