2

我正在尝试进行嵌套findById调用以获取子记录。即使有一个与外部调用返回的文档上的属性匹配的线程,内部也会findById继续返回。我无法弄清楚我在这里做错了什么。null_idpost.threadfindById

这是我的模式:

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

1 回答 1

1

populate()在查询中 运行 a 可能会更好。populate将获取ObjectId并将其相应的文档附加到您的post. 尝试更改为以下内容

架构

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

findById

Post.findById(req.params.post).populate('thread').exec(function (err, post) {
    if (err) return res.send(500, err);
    res.render('posts/edit', post);
});
于 2013-03-29T03:46:58.997 回答