【发布时间】:2021-09-22 16:16:57
【问题描述】:
这是现有架构,在我的节点应用程序中,我已在其中声明了架构中的所有文件
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
【问题讨论】: