【问题标题】:How to modify mongoose schema dynamically, i have to add dynamic fields that are not defined in initial mongoose Schema如何动态修改猫鼬模式,我必须添加初始猫鼬模式中未定义的动态字段
【发布时间】: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

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    你可以使用 .add 方法

    userSchema.add({education: String, age: Number, profile_pic: String});
    

    结帐猫鼬Schema.prototype.add()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-25
      • 1970-01-01
      • 2014-06-01
      • 2018-01-21
      • 2021-05-10
      • 1970-01-01
      • 2021-09-12
      相关资源
      最近更新 更多