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

クエリで a を実行する方がよい場合がありpopulate()ます。 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 に答える