Nested objects in mongoose schemas

前端 未结 2 1142
轮回少年
轮回少年 2020-12-23 14:33

i\'ve seen many answers to this question here, but i still don\'t get it (maybe because they use more \"complex\" examples)... So what im trying to do is a schema for a \"Cu

2条回答
  •  佛祖请我去吃肉
    2020-12-23 15:03

    const mongoose = require('mongoose')
    
    // Make connection
    // https://mongoosejs.com/docs/connections.html#error-handling
    mongoose.connect('mongodb://localhost/test')
    
    // Define schema
    // https://mongoosejs.com/docs/models.html#compiling
    const 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
    // https://mongoosejs.com/docs/models.html#constructing-documents
    const customer = new CustomerModel({
        firstName: 'Ashish',
        lastName: 'Suthar',
        company: 'BitOrbits',
        connectInfo: {
            tel: [
                8154080079,
                6354492692,
            ],
            email: [
                'asissuthar@gmail.com',
                'contact.bitorbits@gmail.com',
            ],
            address: {
                city: 'Radhanpur',
                street: 'Vithalnagar',
                houseNumber: '101',
            },
        },
    })
    
    // Insert customer object
    // https://mongoosejs.com/docs/api.html#model_Model-save
    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
    // https://mongoosejs.com/docs/api.html#model_Model.findOne
    CustomerModel.findOne({ firstName: 'Ashish' }, (err, cust) => {
        if (err) return console.error(err)
    
        // To print stored data
        console.log(cust.connectInfo.tel[0]) // output 8154080079
    })
    
    
    // Update inner record
    // https://mongoosejs.com/docs/api.html#model_Model.update
    CustomerModel.update({ firstName: 'Ashish' }, {
        $set: {
            'connectInfo.tel.0': 8154099999,
        },
    })
    

提交回复
热议问题