这是现有架构,在我的 Node 应用程序中,我在其中声明了架构中的所有字段
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
答案 0 :(得分:1)
您可以使用 .add 方法
userSchema.add({education: String, age: Number, profile_pic: String});