2012-01-24 7 views
4

는 :몽구스 포함 된 문서/DocumentsArrays의 다음 주소로 몽구스 문서에서 ID

DocumentArrays 자신의 _id하여 임베디드 문서를 필터링 특별한 방법 ID를 가지고 http://mongoosejs.com/docs/embedded-documents.html

성명이 부동산 (각각 포함 된 문서는 하나를 얻을 수) :

는 다음 코드를 고려

post.comments.id(my_id).remove(); 
    post.save(function (err) { 
    // embedded comment with id `my_id` removed! 
    }); 

나는 데이터를 검토 한 결과 포함 된 문서에 대한 _id의이 게시물에 의해 확인 될 수있는 것 같은이 없습니다 :

How to return the last push() embedded document

내 질문은 :

설명서가 맞습니까? 만약 그렇다면 어떻게 'my_id'가 '.id (my_id)'을 먼저 수행 하는지를 어떻게 알 수 있습니까?

설명서가 올바르지 않은 경우 문서 배열 내에서 색인을 ID로 사용하는 것이 안전하며 수동으로 고유 ID를 생성해야합니다 (언급 된 게시물 별).

답변

12
대신이 같은 JSON 객체 (몽구스 문서가 제안하는 방식)과 푸시()를 수행하는

:

// create a comment 
post.comments.push({ title: 'My comment' }); 

당신은 당신의 포함 된 개체의 실제 인스턴스를 생성해야하고 push() 대신. 그런 다음 mongoose가 객체가 인스턴스화 될 때 객체를 설정하기 때문에 _id 필드를 직접 가져올 수 있습니다. 여기에 전체 예가 나와 있습니다 :

var mongoose = require('mongoose') 
var Schema = mongoose.Schema 
var ObjectId = Schema.ObjectId 

mongoose.connect('mongodb://localhost/testjs'); 

var Comment = new Schema({ 
    title  : String 
    , body  : String 
    , date  : Date 
}); 

var BlogPost = new Schema({ 
    author : ObjectId 
    , title  : String 
    , body  : String 
    , date  : Date 
    , comments : [Comment] 
    , meta  : { 
     votes : Number 
     , favs : Number 
    } 
}); 

mongoose.model('Comment', Comment); 
mongoose.model('BlogPost', BlogPost); 

var BlogPost = mongoose.model('BlogPost'); 
var CommentModel = mongoose.model('Comment') 


var post = new BlogPost(); 

// create a comment 
var mycomment = new CommentModel(); 
mycomment.title = "blah" 
console.log(mycomment._id) // <<<< This is what you're looking for 

post.comments.push(mycomment); 

post.save(function (err) { 
    if (!err) console.log('Success!'); 
}) 
+0

감사합니다. 그래서 _id가 인스턴스화 된 '주석'(포함 된 문서)의 속성이지만 반드시 데이터베이스의 '필드'는 아닙니다. 내 데이터에는 모델에 대해서만 포함 된 문서의 _id 필드가 없습니다. – Lewis

+0

감사합니다. – Lewis

+0

그러나 이것으로 둘 다 별도의 인스턴스가되지 않습니까? 댓글 모델을 업데이트하면 블로그 모델의 변경 사항이 반영됩니까? – Neikos