【发布时间】:2021-02-10 07:09:17
【问题描述】:
我有用户费用模型,它已经有一些必需的费用,并且可以选择添加更多费用,我通过将模型中的严格标志设置为 true 来添加到 moongodb 模型的动态属性处理。动态属性已成功添加并保存到 mongodb。我也将它们取回,但是当我在 javascript 中访问它时,它给出了 undefined。我花了几个小时但仍然一无所知。模型架构如下。
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);```
【问题讨论】:
-
超出范围,这看起来更像是静态架构而不是动态架构,我建议将您的架构更改为键值对。最近我已回复here 了解更多信息。
-
@turivishal 。但是,就像费用对象中的其他属性一样,例如 [transport],我添加了其他已保存的动态属性。我也将它们取回记录,但是当我访问它时,我说未定义
-
记录的文档是
{ RENT: { amount: 2000, duration: 'MONTHLY' }, FOOD: { amount: 1500, duration: 'WEEKLY' }, TRANSPORT: { amount: 800, duration: 'WEEKLY' }, PHONEBILL: { amount: 800, duration: 'MONTHLY' }, UTILITIES: { amount: 800, duration: 'MONTHLY' }, MISC: { amount: 800, duration: 'MONTHLY' }, EXTRA: { amount: 300, duration: 'MONTHLY' }, MOBILE_INSTALLMENT: { amount: 999, duration: 'MONTHLY' } }