반응형
mongoose 스키마에 중첩된 개체
여기서 이 질문에 대한 답을 많이 봤지만, 아직도 잘 모르겠어요(아마도 더 복잡한 예를 사용하기 때문일 거예요).그래서 '고객'을 위한 스키마로, 이 스키마에는 네스트된 '서브필드'와 반복될 수 있는 다른 두 개의 필드가 있습니다.내 말은 이렇다.
let customerModel = new Schema({
firstName: String,
lastName: String,
company: String,
contactInfo: {
tel: [Number],
email: [String],
address: {
city: String,
street: String,
houseNumber: String
}
}
});
tel 및 e-메일은 배열일 수 있습니다.주소는 반복되지 않지만 보시는 바와 같이 하위 필드가 있습니다.
어떻게 하면 될까요?
const mongoose = require("mongoose");
// Make connection
// https://mongoosejs.com/docs/connections.html#error-handling
mongoose.connect("mongodb://localhost:27017/test", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Define schema
// https://mongoosejs.com/docs/models.html#compiling
const AddressSchema = mongoose.Schema({
city: String,
street: String,
houseNumber: String,
});
const ContactInfoSchema = mongoose.Schema({
tel: [Number],
email: [String],
address: {
type: AddressSchema,
required: true,
},
});
const CustomerSchema = mongoose.Schema({
firstName: String,
lastName: String,
company: String,
connectInfo: ContactInfoSchema,
});
const CustomerModel = mongoose.model("Customer", CustomerSchema);
// 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"],
},
});
// 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.updateOne(
{ firstName: "Ashish" },
{
$set: {
"connectInfo.tel.0": 8154099999,
},
}
);
// 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.
언급URL : https://stackoverflow.com/questions/39596625/nested-objects-in-mongoose-schemas
반응형
'programing' 카테고리의 다른 글
GCD의 dispatch_once in Objective-C를 사용하여 싱글톤을 생성합니다. (0) | 2023.04.25 |
---|---|
목록을 C#의 문자열로 변환합니다. (0) | 2023.04.25 |
Postgre에서 변수를 선언하는 방법SQL 쿼리 (0) | 2023.04.20 |
nodemon이 작동하지 않음: -syslog: nodemon: 명령을 찾을 수 없습니다. (0) | 2023.04.20 |
VBA(excel)의 행을 루프하는 가장 효율적이고 빠른 방법은 무엇입니까? (0) | 2023.04.20 |