Node.js - Mongoose와 관계 만들기
나는 2개의 스키마가 있습니다.Custphone
그리고.Subdomain
.Custphone
belongs_to
a Subdomain
그리고.Subdomain
has_many
Custphones
.
문제는 Mongoose를 사용하여 관계를 만드는 것입니다.제 목표는 custphone.subdomain을 실행하여 custphone이 속한 subdomain을 얻는 것입니다.
내 스키마에는 이런 것이 있습니다.
SubdomainSchema = new Schema
name : String
CustphoneSchema = new Schema
phone : String
subdomain : [SubdomainSchema]
고객 전화 결과를 인쇄하면 다음과 같이 표시됩니다.
{ _id: 4e9bc59b01c642bf4a00002d,
subdomain: [] }
그 때.Custphone
결과는{"$oid": "4e9b532b01c642bf4a000003"}
MongoDB에서.
하고싶다custphone.subdomain
그리고 고객 전화의 하위 도메인 개체를 가져옵니다.
Mongoose의 새로운 채우기 기능을 사용해 보려고 하는 것 같습니다.
위의 예를 사용하여:
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
SubdomainSchema = new Schema
name : String
CustphoneSchema = new Schema
phone : String
subdomain : { type: ObjectId, ref: 'SubdomainSchema' }
그subdomain
필드가 다음과 같은 '_id'로 업데이트됩니다.
var newSubdomain = new SubdomainSchema({name: 'Example Domain'})
newSubdomain.save()
var newCustphone = new CustphoneSchema({phone: '123-456-7890', subdomain: newSubdomain._id})
newCustphone.save()
실제로 데이터를 가져오려면subdomain
조금 더 복잡한 쿼리 구문을 사용해야 하는 필드:
CustphoneSchema.findOne({}).populate('subdomain').exec(function(err, custPhone) {
// Your callback code where you can access subdomain directly through custPhone.subdomain.name
})
비슷한 문제가 있어서 mongoose의 Model.findByIdAndUpdate()를 사용해야 했습니다.
문서: http://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate
이 게시물은 또한 저에게 도움이 되었습니다: http://blog.ocliw.com/2012/11/25/mongoose-add-to-an-existing-array/comment-page-1/ #http-http12.
언급URL : https://stackoverflow.com/questions/7810892/node-js-creating-relationships-with-mongoose
'programing' 카테고리의 다른 글
항목의 길이가 다른 사전에서 데이터 프레임 작성 (0) | 2023.06.07 |
---|---|
Argparse 인수에 대한 특정 값 허용 (0) | 2023.06.07 |
wp 정의되지 않은 함수 add_infined_section (0) | 2023.06.07 |
Ts-node : 구문 오류: 모듈 외부에서 가져오기 문을 사용할 수 없습니다. (0) | 2023.06.07 |
현재 시스템을 가져옵니다.HttpContext의 Web.UI.Page? (0) | 2023.06.07 |