猫鼬模式中的嵌套对象
问题描述:
我已经在这里看到这个问题的很多答案,但我仍然没有得到它(可能是因为他们使用更多“复杂”的例子)... 所以即时尝试做的是“客户”模式,它将有两个字段嵌套“子字段”,以及其他可能重复的字段。这里就是我的意思是:猫鼬模式中的嵌套对象
let customerModel = new Schema({
firstName: String,
lastName: String,
company: String,
contactInfo: {
tel: [Number],
email: [String],
address: {
city: String,
street: String,
houseNumber: String
}
}
});
电话:和电子邮件可能是一个数组。 和地址不会重复,但有一些子字段,你可以看到。
我该如何做这项工作?
答
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}}
);
答
// 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
如何做到这一点任何意见: https://stackoverflow.com/questions/48753436/dynamic-mongodb-schema-object-creation-in-angularjs – CodeHunter