[英]How to modify mongoose schema dynamically, i have to add dynamic fields that are not defined in initial mongoose Schema
這是現有架構,在我的節點應用程序中,我已經在架構中聲明了所有文件
const userSchema = new mongoose.Schema({
username: String,
password: String,
interests: String
});
創建以下文檔
{
"_id" : ObjectId("60edab731ba3623280f4aead"),
"username" : "a@a.com",
"hash" : "4753f142aac6f912812d1cc79",
"__v" : NumberInt(0),
"interests" : "Fishing, Reading"
}
現在我為用戶添加了更多字段,如教育、年齡、個人資料照片等,輸出文檔應如下所示。
{
"_id" : ObjectId("60edab731ba3623280f4aead"),
"username" : "a@a.com",
"hash" : "4753f142aac6f912812d1cc79",
"__v" : NumberInt(0),
"interest1" : "Fishing",
"education" : "Some Edutation",
"age" : 35,
"profile_pic": "https://image-link.jpg"
}
最簡單的解決方案是返回並手動將架構更新為必填字段,如下所示
const userSchema = new mongoose.Schema({
username: String,
password: String,
interests: String,
education: String,
age: Number,
profile_pic: String
});
但是如何動態執行此操作,以便我可以將新數據動態添加到文檔中並在模式中不存在時創建新文件? 我知道如果直接使用 mongoDB 我不必擔心 Schemas 但我在這里使用 Mongoose
您可以使用 .add 方法
userSchema.add({education: String, age: Number, profile_pic: String});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.