猫鼬模式中的嵌套对象 [英] Nested objects in mongoose schemas

查看:74
本文介绍了猫鼬模式中的嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里看到了很多关于这个问题的答案,但是我仍然不明白(也许是因为他们使用了更多复杂"的例子)... 因此,我试图做的是为客户"建立模式,它将有两个将嵌套子字段"的字段,而其他字段可能会重复.这是我的意思:

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 "Customer", and it will have two fields that will have nested "subfields", and others that may repeat. here is what i mean:

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

电话电子邮件可能是一个数组. 和地址将不会重复,但是您会看到一些子字段.

tel and email might be an array. and address will not be repeated, but have some sub fields as you can see.

我该如何进行这项工作?

How can i make this work?

推荐答案

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: ['me@a.com','you@a.com'],
        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}}
    );

这篇关于猫鼬模式中的嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆