首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用nodejs访问添加到mongoDb模型的动态属性

使用nodejs访问添加到mongoDb模型的动态属性
EN

Stack Overflow用户
提问于 2021-02-10 15:09:17
回答 1查看 60关注 0票数 0

我有一个用户费用模型,它已经有了一些所需的费用,并且可以选择添加更多的费用,我可以通过动态属性添加到moongodb模型中,通过在模型中设置true的严格标志来处理这些费用。动态属性被成功地添加并保存到mongodb中,.I也将它们取回,但当我在javascript中访问它时,它给出未定义。我已经花了几个小时,但仍然一无所知。模型架构如下。

代码语言:javascript
复制
const {
  TRANSPORT,
  FOOD,
  PHONEBILL,
  UTILITIES,
  MISC,
  MONTHLY,
  WEEKLY,
  RENT,
} = require("../constants");
const semesterPlanSchema = new mongoose.Schema(
  {
    expense: {
      [RENT]: {
        amount: Number,
        duration: {
          type: String,
          enum: [WEEKLY, MONTHLY],
        },
      },
      [FOOD]: {
        amount: Number,
        duration: {
          type: String,
          enum: [WEEKLY, MONTHLY],
        },
      },
      [TRANSPORT]: {
        amount: Number,
        duration: {
          type: String,
          enum: [WEEKLY, MONTHLY],
        },
      },
      [PHONEBILL]: {
        amount: Number,
        duration: {
          type: String,
          enum: [WEEKLY, MONTHLY],
        },
      },
      [UTILITIES]: {
        amount: Number,
        duration: {
          type: String,
          enum: [WEEKLY, MONTHLY],
        },
      },
      [MISC]: {
        amount: Number,
        duration: {
          type: String,
          enum: [WEEKLY, MONTHLY],
        },
      },
    },
    month: {
      type: Number,
      enum: [1, 2, 3, 4, 5],
    },
    user_id: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "user",
    },
    // will be used in emergency fund request
    // to check which plan month is currently active(1-5)
    isActive: {
      type: Boolean,
      default: false,
    },
    expired: {
      type: Boolean,
      default: false,
    },
    grand_total: {
      type: Number,
    },
    start_date: {
      type: String,
    },
  },
  {
    timestamps: true,
    strict: false,
  }
);

module.exports = mongoose.model("semesterplan", semesterPlanSchema);```
EN

回答 1

Stack Overflow用户

发布于 2021-02-10 17:27:59

要读取在strict:false的帮助下添加的属性,应该在文档上使用get([path])方法。

假设您的文档被读取并存储到变量semesterPlan中。并且新动态属性的名称是例如otherExpenses,那么要读取属性值,您应该使用semesterPlan.get("otherExpenses")

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66132338

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档