programing

Mongoose - ObjectId 배열에 채우기 사용

kakaobank 2023. 5. 2. 22:52
반응형

Mongoose - ObjectId 배열에 채우기 사용

다음과 같은 스키마가 있습니다.

var conversationSchema = new Schema({
    created: { type: Date, default: Date.now },
    updated: { type: Date, default: Date.now },
    recipients: { type: [Schema.ObjectId], ref: 'User' },
    messages: [ conversationMessageSchema ]
});

즉, 수신자 컬렉션은 사용자 스키마/ 컬렉션을 참조하는 개체 ID의 컬렉션입니다.

쿼리에 이 정보를 입력해야 하므로 다음과 같이 시도합니다.

Conversation.findOne({ _id: myConversationId})
.populate('user')
.run(function(err, conversation){
    //do stuff
});

하지만 분명히 '사용자'는 인구가 많지 않습니다.

제가 이걸 할 수 있는 방법이 있을까요?

이 질문을 마주치는 다른 사람들에게..OP의 코드에 스키마 정의에 오류가 있습니다.다음과 같아야 합니다.

var conversationSchema = new Schema({
    created: { type: Date, default: Date.now },
    updated: { type: Date, default: Date.now },
    recipients: [{ type: Schema.ObjectId, ref: 'User' }],
    messages: [ conversationMessageSchema ]
});
mongoose.model('Conversation', conversationSchema);

컬렉션 이름 대신 스키마 경로의 이름을 사용합니다.

Conversation.findOne({ _id: myConversationId})
.populate('recipients') // <==
.exec(function(err, conversation){
    //do stuff
});

언급URL : https://stackoverflow.com/questions/10568281/mongoose-using-populate-on-an-array-of-objectid

반응형