[英]How to save particular object in mongoose schema
我在這里遇到了一些問題,我嘗試只存儲一個 object 無論是學校還是大學還是工作,但是 mongoose 會自動創建另外兩個 object。
如何省略其他object。這里我應該使用default
let mySchema = new Schema({
"type": { type: String, default: "" }, // school or college or work
"school": {
'name':{ type: String, default: "" },
'parent':{ type: String, default: "" },
'address':{ type: String, default: "" },
'email_id':{ type: String, default: "" },
'phone_no':{ type: String, default: "" },
},
"college": {
'name':{ type: String, default: "" },
'friend':{ type: String, default: "" },
'address':{ type: String, default: "" },
'email_id':{ type: String, default: "" },
'phone_no':{ type: String, default: "" },
},
"work": {
'name':{ type: String, default: "" },
'colleague':{ type: String, default: "" },
'address':{ type: String, default: "" },
'email_id':{ type: String, default: "" },
'phone_no':{ type: String, default: "" },
},
});
是否有什么東西阻止你以編程方式設置它?
const myType = "school"; // Just for example const mySchemaObj = { "type": { type: String, default: myType } }; mySchemaObj[myType] = { "school": { 'name':{ type: String, default: "" }, 'parent':{ type: String, default: "" }, 'address':{ type: String, default: "" }, 'email_id':{ type: String, default: "" }, 'phone_no':{ type: String, default: "" }, }, "college": { 'name':{ type: String, default: "" }, 'friend':{ type: String, default: "" }, 'address':{ type: String, default: "" }, 'email_id':{ type: String, default: "" }, 'phone_no':{ type: String, default: "" }, }, "work": { 'name':{ type: String, default: "" }, 'colleague':{ type: String, default: "" }, 'address':{ type: String, default: "" }, 'email_id':{ type: String, default: "" }, 'phone_no':{ type: String, default: "" }, } }[myType]; console.log(mySchemaObj); /* Then, later... let mySchema = new Schema(mySchemaObj); */
如果您從 Mongoose 文檔中查看此部分,您將看到 Mongoose 總是為嵌套文檔(例如school
)創建一個空的 object。
您可以改用子文檔,其中school
、 college
和work
是Schema
的實例。
你可以做什么:
const mySchema = new Schema({
school: new Schema({
name: { type: String },
parent: { type: String },
address: { type: String },
email_id: { type: String },
phone_no: { type: String },
}),
college: new Schema({
name: { type: String },
friend: { type: String },
address: { type: String },
email_id: { type: String },
phone_no: { type: String },
}),
work: new Schema({
name: { type: String },
colleague: { type: String },
address: { type: String },
email_id: { type: String },
phone_no: { type: String },
}),
});
const MyModel = mongoose.model('MyModel', mySchema);
const myDocument = new MyModel();
myDocument.college = { name: 'Harvard' };
await myDocument.save();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.