Node.js-Mongoose로 관계 만들기
2 개의 스키마 Custphone와 Subdomain. Custphone belongs_toa Subdomain및 Subdomain has_many Custphones.
문제는 Mongoose를 사용하여 관계를 만드는 것입니다. 내 목표는 custphone.subdomain을 수행하고 Custphone이 속한 하위 도메인을 가져 오는 것입니다.
내 스키마에 다음이 있습니다.
SubdomainSchema = new Schema
name : String
CustphoneSchema = new Schema
phone : String
subdomain : [SubdomainSchema]
Custphone 결과를 인쇄하면 다음과 같은 결과가 나타납니다.
{ _id: 4e9bc59b01c642bf4a00002d,
subdomain: [] }
Custphone결과가 {"$oid": "4e9b532b01c642bf4a000003"}MongoDB에 있을 때 .
내가하고 싶은 custphone.subdomain와 custphone의 하위 도메인 개체를 얻을.
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/#comment-17812
참고 URL : https://stackoverflow.com/questions/7810892/node-js-creating-relationships-with-mongoose
'Program Club' 카테고리의 다른 글
| 아파치의 httpd.conf 파일에서 변수를 정의하는 방법은 무엇입니까? (0) | 2020.12.11 |
|---|---|
| 특정 디렉토리의 경로없이 파일 이름 가져 오기 (0) | 2020.12.11 |
| Go에서 런타임에 해당 유형에서 구조체의 새 인스턴스를 만드는 방법은 무엇입니까? (0) | 2020.12.11 |
| CSS-최대 Z- 색인 값 (0) | 2020.12.11 |
| 현재 IPython 노트북 이름을 얻는 방법 (0) | 2020.12.11 |