Mongoose:嵌套的findById返回null

时间:2013-03-28 21:59:32

标签: mongoose

我正在尝试进行嵌套findById调用以获取子记录。内部findById会一直返回null,即使有一个_id与外部post.thread调用返回的文档上的findById属性相匹配的帖子。我无法弄清楚我在这里做错了什么。

以下是我的架构:

PostSchema = new mongoose.Schema({
    title: { type: String, required: true },
    message: { type: String },
    thread: { type: mongoose.Schema.Types.ObjectId, required: true }
});

ThreadSchema = new mongoose.Schema({
    url: { type: String, required: true, unique: true },
    title: String,
    pageCount: Number,
    thingsTheySaid: Array,
    lastScraped: Date
});

这是我正在尝试执行的代码:

Post.findById(req.params.post).lean().exec(function (err, post) {
    if (err) return res.send(500, err);
    Thread.findById(post.thread).lean().exec(function (err, thread) {
        if (err) return res.send(500, err);
        // thread is always null here, instead of the expected lean object
        if (!thread) return res.send(500, 'thread not found');
        post.thread = thread;

        res.render('posts/edit', post);
    });
});

这是mongo CLI中显示的数据:

// post
{ 
    "title" : "C1", 
    "thread" : ObjectId("5154b8bc741aa70000000001"), 
    "_id" : ObjectId("5154b8bf741aa70000000002"), 
    "__v" : 0 
}

// thread
{ 
    "lastScraped" : ISODate("2013-03-28T21:23:22.750Z"), 
    "pageCount" : 15, 
    "title" : "GDT: Game #25 : Kings @ Coyotes - Tuesday,  3/12/�13 @ 7:00 pm PDT - HFBoards", 
    "url" : "http://hfboards.hockeysfuture.com/showthread.php?t=1373783", 
    "_id" : ObjectId("5154b4cae60b210000000001"), 
    "thingsTheySaid" : [ /*snipped for Brevity*/ ]
}

使用populate()

的解决方案

nevi_me使用populate()函数在正确的轨道上,但这是我最终用来解决问题的代码。

PostSchema = new mongoose.Schema({
    title: { type: String, required: true },
    message: { type: String },
    thread: { type: mongoose.Schema.Types.ObjectId, ref: 'Thread', required: true }
});

Post.findById(req.params.post).populate('thread').exec(function (err, post) {
    if (err) return res.send(500, err);
    res.render('posts/edit', post);
});

1 个答案:

答案 0 :(得分:1)

在查询中运行populate()可能会更好。 populateObjectId post并将相应的文档附加到您的PostSchema = new mongoose.Schema({ title: { type: String, required: true }, message: { type: String }, thread: { type: mongoose.Schema.Types.ObjectId, ref: 'Thread', required: true } }); 。尝试更改为以下

<强>模式

Post.findById(req.params.post).populate('thread').exec(function (err, post) {
    if (err) return res.send(500, err);
    res.render('posts/edit', post);
});

<强> findById

{{1}}