Mongoose: 스키마 필드를 ID로 설정하는 방법은 무엇입니까?
다음 스키마가 지정된 경우:
var UserSchema = new Schema({
, email : { type: String }
, passwordHash : { type: String }
, roles : { type: [String] }
});
싶다email
열쇠가 될 겁니다이것을 어떻게 정의해야 합니까?
할 수 있습니다.
var UserSchema = new Schema({
, _id: { type: String }
, passwordHash : { type: String }
, roles : { type: [String] }
});
그래서 MongoDB는 그것을 id-field로 인식하고, 내 코드를 참조하도록 조정할 것입니다._id
대신에email
하지만 그것은 저에게 깨끗하다고 느껴지지 않습니다.
누구라도 있나요?
Mongoose를 사용하고 있기 때문에 한 가지 옵션은 이메일 문자열을 사용하는 것입니다._id
필드를 선택한 다음 가상 필드를 추가합니다.email
그것은 그것을 반환합니다._id
전자 메일을 사용하는 코드를 정리합니다.
var userSchema = new Schema({
_id: {type: String},
passwordHash: {type: String},
roles: {type: [String]}
});
userSchema.virtual('email').get(function() {
return this._id;
});
var User = mongoose.model('User', userSchema);
User.findOne(function(err, doc) {
console.log(doc.email);
});
Mongoose 문서를 일반 JS 오브젝트 또는 JSON 문자열로 변환할 때 가상 필드는 기본적으로 포함되지 않습니다.이 값을 포함하려면 다음 값을 설정해야 합니다.virtuals: true
또는 호출의 옵션:
var obj = doc.toObject({ virtuals: true });
var json = doc.toJSON({ virtuals: true });
언급URL : https://stackoverflow.com/questions/10352900/mongoose-how-to-set-a-schema-field-to-be-the-id
'programing' 카테고리의 다른 글
'HTMLInputElement'에서 'value' 속성을 설정하지 못했습니다. (0) | 2023.07.03 |
---|---|
AUTO_INCREMENT가 Maria에서 작동하지 않습니다.DB (0) | 2023.07.03 |
Oracle에서 시간이 없는 날짜 유형 (0) | 2023.07.03 |
mongodb 업데이트에서 변수 사용 (0) | 2023.06.28 |
null 가능한 열에 대한 인덱스 (0) | 2023.06.28 |