2016-12-16 19 views
0

저는 NodeJS & MongoDB를 처음 사용합니다. 아마도이 질문은 이미 요청되었지만 간단한 대답이 될 수 없었습니다. 그렇다면 미안합니다.MongoDB + NodeJS 외래 키 전체 문서

내가 그렇게 찾고 스키마 작업입니다 :

var usersSchema    = new mongoose.Schema({ 
    profile   : { 
     email    : {type: String, default: ''}, 
     password   : {type: String, default: ''}, 
     firstName   : {type: String, default: ''}, 
    }, 
    friends   : [{ 
     type    : mongoose.Schema.Types.ObjectId, 
     ref     : 'usersSchema' 
    }], 
    pets   : [{ 
     type    : mongoose.Schema.Types.ObjectId, 
     ref     : 'petsSchema' 
    }], 
}); 

1) 있음)의 사용자는 누구인지, 자신을 다스 려 스키마가 (여기에 사용자가 친구의 목록을 참조 할 수 있습니까? 나는 그것에 대한 어떤 대답도 찾지 못했지만 확실히 확신한다.

2) 실제로 애완 동물의 ObjectID 목록을 가져오고 있지만 이름, 혈통과 같은 다른 속성은 없습니다. 요청에서 전체 Pets 문서를로드 할 수 있습니까?

User.findOne({ 'profile.email' : req.user.profile.email }).populate('Pets').exec(function(err, user){ .... 

==> 이것은 애완 동물의 개체 ID 만 반환합니다.

답장을 보내 주셔서 감사합니다. 좋은 하루 되세요!

답변

0

심판에서 스키마 이름을 지정하는 중 문제가 발생합니다. 모델 이름을 지정해야합니다.

몽구스 사이트

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

var personSchema = Schema({ 
    _id  : Number, 
    name : String, 
    age  : Number, 
    stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }] 
}); 

var storySchema = Schema({ 
    _creator : { type: Number, ref: 'Person' }, 
    title : String, 
    fans  : [{ type: Number, ref: 'Person' }] 
}); 

var Story = mongoose.model('Story', storySchema); 
var Person = mongoose.model('Person', personSchema); 

에 예와 같이 그리고 당신이 당신의 스키마를 가지고가는 경우에이 코드를 아래와 같이 보일 것으로

.

var petSchema = new mongoose.Schema({ 
 
\t firstName: { 
 
\t \t type: String, 
 
\t \t default: '' 
 
\t }, 
 
\t pedigree: { 
 
\t \t type: String, 
 
\t \t default: '' 
 
\t } 
 
}); 
 

 

 
var usersSchema = new mongoose.Schema({ 
 
\t profile: { 
 
\t \t email: { 
 
\t \t \t type: String, 
 
\t \t \t default: '' 
 
\t \t }, 
 
\t \t password: { 
 
\t \t \t type: String, 
 
\t \t \t default: '' 
 
\t \t }, 
 
\t \t firstName: { 
 
\t \t \t type: String, 
 
\t \t \t default: '' 
 
\t \t }, 
 
\t }, 
 

 
\t friends: [{ 
 
\t \t type: mongoose.Schema.Types.ObjectId, 
 
\t \t ref: 'User' 
 
\t }], 
 

 
\t pets: [{ 
 
\t \t type: mongoose.Schema.Types.ObjectId, 
 
\t \t ref: 'Pet' 
 
\t }] 
 
}); 
 

 

 
// we need to create a model to use it 
 
var User = mongoose.model('User', UserSchema); 
 
var Pet = mongoose.model('Pet', petSchema);

+0

안녕하세요 내가 따라 스키마를 변경, 대답 주셔서 감사합니다. 그러나 그것은 작동하지 않는 것 같습니다. 나는 항상 객체의 ID가 아닌 객체의 내용을 가져오고있다. 그래서 개체 ID 키로 선택하는 Pet 테이블의 개체를 선택해야하는 것처럼 보입니다. –