반응형
Mongoose 스키마에서 다른 스키마를 참조하는 방법은 무엇입니까?
저는 데이트 앱을 위해 몽구스 스키마를 만들고 있습니다.
각각 갖고 싶어요person방문한 모든 이벤트에 대한 참조를 포함하는 문서, 어디에events는 시스템에 자체 모델이 있는 또 다른 스키마입니다.스키마에서 이것을 어떻게 설명할 수 있습니까?
var personSchema = mongoose.Schema({
firstname: String,
lastname: String,
email: String,
gender: {type: String, enum: ["Male", "Female"]}
dob: Date,
city: String,
interests: [interestsSchema],
eventsAttended: ???
});
모집단을 사용하여 이 작업을 수행할 수 있습니다.
채우기는 문서에서 지정된 경로를 다른 컬렉션의 문서로 자동 변경하는 프로세스입니다.단일 문서, 다중 문서, 일반 개체, 다중 일반 개체 또는 쿼리에서 반환된 모든 개체를 채울 수 있습니다.
이벤트 스키마가 다음과 같이 정의되었다고 가정합니다.
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var eventSchema = Schema({
title : String,
location : String,
startDate : Date,
endDate : Date
});
var personSchema = Schema({
firstname: String,
lastname: String,
email: String,
gender: {type: String, enum: ["Male", "Female"]}
dob: Date,
city: String,
interests: [interestsSchema],
eventsAttended: [{ type: Schema.Types.ObjectId, ref: 'Event' }]
});
var Event = mongoose.model('Event', eventSchema);
var Person = mongoose.model('Person', personSchema);
채우기가 사용되는 방법을 표시하려면 먼저 사용자 개체를 만듭니다.
aaron = new Person({firstname: 'Aaron'})그리고 이벤트 객체,
event1 = new Event({title: 'Hackathon', location: 'foo'}):
aaron.eventsAttended.push(event1);
aaron.save(callback);
그런 다음 쿼리를 만들 때 다음과 같이 참조를 채울 수 있습니다.
Person
.findOne({ firstname: 'Aaron' })
.populate('eventsAttended') // only works if we pushed refs to person.eventsAttended
.exec(function(err, person) {
if (err) return handleError(err);
console.log(person);
});
다른 테이블에서 한 테이블의 ObjectId를 참조하려면 아래 코드를 참조하십시오.
const mongoose = require('mongoose'),
Schema=mongoose.Schema;
const otpSchema = new mongoose.Schema({
otpNumber:{
type: String,
required: true,
minlength: 6,
maxlength: 6
},
user:{
type: Schema.Types.ObjectId,
ref: 'User'
}
});
const Otp = mongoose.model('Otp',otpSchema);
// Joi Schema For Otp
function validateOtp(otp) {
const schema = Joi.object({
otpNumber: Joi.string().max(6).required(),
userId: Joi.objectId(), // to validate objectId we used 'joi-objectid' npm package
motive: Joi.string().required(),
isUsed: Joi.boolean().required(),
expiresAt: Joi.Date().required()
});
// async validate function for otp
return schema.validateAsync(otp);
}
exports.Otp = Otp;
exports.validateOtp = validateOtp;
리스트 항목
var personSchema = mongoose.Schema({
firstname: String,
lastname: String,
email: String,
gender: {
type: String,
enum: ["Male", "Female"]
}
dob: Date,
city: String,
interests: [interestsSchema],
eventsAttended[{
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: "Place"
}],
**//ref:"Places"...you have put the other model name**
*OR*
eventsAttended[{
type: mongoose.Types.ObjectId,
required: true,
ref: "Place"
}],
});
언급URL : https://stackoverflow.com/questions/29078753/how-to-reference-another-schema-in-my-mongoose-schema
반응형
'codememo' 카테고리의 다른 글
| [] 및 {} vs list()와 dict() 중 어떤 것이 더 낫습니까? (0) | 2023.05.18 |
|---|---|
| 옵션 매개 변수를 오버로드로 대체하는 것이 획기적인 변화입니까? (0) | 2023.05.18 |
| Bash에서 $PATH 변수에서 경로를 제거하는 가장 우아한 방법은 무엇입니까? (0) | 2023.05.18 |
| VBA를 사용하여 Excel의 조건부 서식에서 배경색을 가져오는 방법 (0) | 2023.05.18 |
| Bash에서 명령어의 단일 따옴표 내 변수 확장 (0) | 2023.05.18 |