[javascript] Mongoose에서 다른 스키마 참조

다음과 같은 두 개의 스키마가있는 경우 :

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



답변

채우기 방법이 당신이 찾고있는 것 같습니다. 먼저 게시물 스키마를 약간 변경합니다.

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
});


답변

부록 : “인구”를 언급 한 사람은 아무도 없습니다. — 몽구스 채우기 방법을 살펴 보는 것은 시간과 돈의 가치가 매우 높습니다. 참조하는 교차 문서도 설명합니다.

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


답변

늦은 답장이지만 Mongoose에는 하위 문서 의 개념도 있습니다.

이 구문을 사용하면 다음과 userSchema같이 유형 으로 참조 할 수 있습니다 postSchema.

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

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

postedBy유형이 있는 업데이트 된 필드를 확인합니다 userSchema.

이렇게하면 게시물에 사용자 개체가 포함되어 참조를 사용하여 필요한 추가 조회가 절약됩니다. 때로는 이것이 더 좋을 수 있고, 다른 경우에는 ref / populate 경로가 갈 길일 수 있습니다. 응용 프로그램이 수행하는 작업에 따라 다릅니다.


답변