2
중첩 된 findById
호출을 수행하여 하위 레코드를 가져 오려고합니다. 내부 findById
은 외부 findById
호출에 의해 반환 된 문서의 post.thread
속성과 일치하는 _id
의 스레드가 있어도 null
을 계속 반환합니다. 나는 내가 여기서 잘못하고있는 것을 알아낼 수 없다.몽구스 : 중첩 된 findById가 null을 반환합니다.
// 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*/ ]
}
다음 몽고의 CLI 같이
다음
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);
});
});
데이터를이다 : 여기
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
});
내가 실행하기 위해 노력하고있어 코드입니다 : 여기
내 스키마입니다
용액 사용 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);
});
감사를보십시오! 귀하의 코드가 나를 위해 작동하지 않았지만 populate()가 트릭을 했으므로 답변에 대한 크레딧을드립니다. –
@CraigM 게시 문서의 구조가 정확히 같을 것이라고 기대하지 않았으므로이 문서를 조정해야 할 수도 있습니다. 내 대답을 내가 한 일로 업데이트하여 나중에 다른 사람이 정답을 얻을 수 있도록 할 수 있습니다. 감사합니다. –
감사합니다. 그것은 문제가되는 스키마가 아니 었습니다. populate 메소드가 Mongoose Model 객체에 없다는 것입니다 (예제에서는 Post). 그것은 Document 객체에 있습니다. populate는 나의 문제를 해결하는 열쇠였다. 당신의 대답을 업데이트했습니다. 다시 한번 감사드립니다. –