2016-09-20 6 views
7

이 질문에 대한 많은 답변을 보았습니다.하지만 더 많은 "복잡한"예제를 사용했기 때문에 여전히 이해가되지 않습니다. 그래서 무엇을하려고합니까? "고객"에 대한 스키마를 포함하고 중첩 된 "하위 필드"가있는 두 개의 필드와 반복 될 수있는 다른 필드가 있습니다.몽구스 스키마의 중첩 된 객체

let customerModel = new Schema({ 
    firstName: String, 
    lastName: String, 
    company: String, 
    contactInfo: { 
     tel: [Number], 
     email: [String], 
     address: { 
      city: String, 
      street: String, 
      houseNumber: String 
     } 
    } 
}); 

전화이메일을 배열 할 수 있습니다 여기에 내가 무엇을 의미입니다. 및 주소는 반복되지 않지만 볼 수있는 것처럼 일부 하위 필드가 있습니다.

어떻게하면됩니까?

답변

5
var mongoose = require('mongoose'); 

mongoose.connect('mongodb://localhost/test'); 

var CustomerModel = mongoose.model('CustomerModel', { 
    firstName: String, 
    lastName: String, 
    company: String, 
    connectInfo: { 
     tel: [Number], 
     email: [String], 
     address: { 
      city: String, 
      street: String, 
      houseNumber: String 
     } 
    } 
}); 

//create a record 
var customer = new CustomerModel({ 
    firstName: 'Ashish', 
    lastName: 'Suthar', 
    company: 'asis', 
    connectInfo: { 
     tel: [12345,67890], 
     email: ['[email protected]','[email protected]'], 
     address: { 
      city: 'x', 
      street: 'y', 
      houseNumber: 'x-1' 
     } 
    } 
}); 

//insert customer object 
customer.save((err,cust) => { 
    if(err) return console.error(err); 

    //this will print inserted record from database 
    //console.log(cust); 
}); 


// display any data from CustomerModel 
CustomerModel.findOne({firstName:'Ashish'}, (err,cust) => { 
    if(err) return console.error(err); 

    //to print stored data 
    console.log(cust.connectInfo.tel[0]); //output 12345 
}); 


//update inner record 
CustomerModel.update(
    {firstName: 'Ashish'}, 
    {$set: {"connectInfo.tel.0": 54320}} 
    ); 
+0

이 작업을 수행하는 방법에 대한 의견 : https://stackoverflow.com/questions/48753436/dynamic-mongodb-schema-object-creation-in-angularjs – CodeHunter

2
// address model 
    var addressModelSchema = new Schema({ 
       city: String, 
       street: String, 
       houseNumber: String}) 
    mongoose.model('address',addressModelSchema ,'address') 

// contactInfo model 
     var contactInfoModelSchema = new Schema({ 
      tel: [Number], 
      email: [String], 
      address : { 
        type : mongoose.Schema.Type.ObjectId, 
        ref:'address' 
         } 
       }) 
    mongoose.model('contactInfo ',contactInfoModelSchema ,'contactInfo ') 

// customer model 
    var customerModelSchema = new Schema({ 
     firstName: String, 
     lastName: String, 
     company: String, 
     contactInfo : { 
    type : mongoose.Schema.Type.ObjectId, 
    ref:'contactInfo ' 
    } 
    }); 
    mongoose.model('customer',customerModelSchema ,'customer') 

//add new address then contact info then the customer info 
// it is better to create model for each part. 
+0

이에 대한 의견 : https://stackoverflow.com/questions/48753436/dynamic-mongodb-schema-object-creation-in-angularjs – CodeHunter