我有一个用户费用模型,它已经有了一些所需的费用,并且可以选择添加更多的费用,我可以通过动态属性添加到moongodb模型中,通过在模型中设置true的严格标志来处理这些费用。动态属性被成功地添加并保存到mongodb中,.I也将它们取回,但当我在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);```发布于 2021-02-10 17:27:59
要读取在strict:false的帮助下添加的属性,应该在文档上使用get([path])方法。
假设您的文档被读取并存储到变量semesterPlan中。并且新动态属性的名称是例如otherExpenses,那么要读取属性值,您应该使用semesterPlan.get("otherExpenses")
https://stackoverflow.com/questions/66132338
复制相似问题