복붙노트

[MONGODB] 몽구스의 다른 스키마를 참조하는

MONGODB

몽구스의 다른 스키마를 참조하는

내가 좋아하는 두 스키마가있는 경우 :

var userSchema = new Schema({
    twittername: String,
    twitterID: Number,
    displayName: String,
    profilePic: String,
});

var  User = mongoose.model('User') 

var postSchema = new Schema({
    name: String,
    postedBy: User,  //User Model Type
    dateCreated: Date,
    comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});

나는 위의 예처럼 그들을 함께 연결을 시도하지만 난 그것을 할 방법을 알아낼 수 없었다. 나는 이런 식으로 뭔가를 할 수 있다면 결국, 아주 쉽게 내 인생을 만들 것

var profilePic = Post.postedBy.profilePic

해결법

  1. ==============================

    1.채우기 방법은 당신이 찾고있는 무엇을 것 같은데. 첫 번째 게시물 스키마에 작은 변화를 만들 :

    채우기 방법은 당신이 찾고있는 무엇을 것 같은데. 첫 번째 게시물 스키마에 작은 변화를 만들 :

    var postSchema = new Schema({
        name: String,
        postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
        dateCreated: Date,
        comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
    });
    

    그런 다음 모델을 :

    var Post = mongoose.model('Post', postSchema);
    

    당신이 당신의 쿼리를 할 때 그런 다음,이 같은 참조를 채울 수 있습니다 :

    Post.findOne({_id: 123})
    .populate('postedBy')
    .exec(function(err, post) {
        // do stuff with post
    });
    
  2. ==============================

    2.부록 : 아니오 하나는 몽구스 채우기 방법을보고 매우 가치가 시간과 돈이다 --- "채우기"를 언급 : 또한 참조 교차 문서를 설명

    부록 : 아니오 하나는 몽구스 채우기 방법을보고 매우 가치가 시간과 돈이다 --- "채우기"를 언급 : 또한 참조 교차 문서를 설명

    http://mongoosejs.com/docs/populate.html

  3. from https://stackoverflow.com/questions/18001478/referencing-another-schema-in-mongoose by cc-by-sa and MIT license