【发布时间】:2021-10-06 11:29:47
【问题描述】:
我想存储一组嵌套的子文档,例如下面的一个:
[
{"2021-02-01income":{"value":37.95,"tax":0,"type":"income"}},
{"2021-03-01income":{"value":38.25,"tax":0,"type":"income"}},
{"2021-03-08fund": {"value":-78,"type":"fund","transaction":"610378deead56742a898443b"}},
{"2021-04-01income":{"value":38.53,"tax":0,"type":"income"}},
{"2021-07-01income":{"type":"income","tax":0,"value":134}},
]
我想出了以下不起作用的架构,因为您可以看到对象数组基于唯一键嵌套对象... 有什么我可以尝试的解决方法:
const incomeSchema = mongoose.Schema({
type: { type: String, required: true },
value: { type: Number, required: true },
tax: { type: Number, required: false },
transaction: {
type: mongoose.Schema.Types.ObjectId,
required: false,
ref: 'Transaction',
},
});
const investmentSchema = mongoose.Schema(
{
incomes: [{ type: incomeSchema }],
name: { type: String, required: true },
user: {
type: mongoose.Schema.Types.ObjectId,
required: false,
ref: 'User',
},
account: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Account',
},
broker: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Broker',
},
type: { type: String, required: true },
rate: { type: String, required: true },
indexer: { type: String, required: true },
investment_date: { type: Date, required: true },
due_date: { type: Date, required: true },
initial_amount: { type: Number, required: true },
accrued_income: { type: Number, required: false, default: 0 },
taxes: { type: Number, required: false, default: 0 },
},
{ timestamps: true }
);
const Investment = mongoose.model('Investment', investmentSchema);
【问题讨论】:
-
在 mongoose 字段名称应该是预先定义的。这意味着“2021-02-01income”字段不能有动态字段名称
-
好的,@Prana ...我明白了,但也许还有其他解决方案...因为当它恰好是基金时,我需要存储一个对象 Id ref 属性,即交易字段...发生的情况是,当我之前试图将其保存为 simpe objects 数组时,我无法检索已经存在的对象 ID ......而且我无法使用函数 mongoose.Types.ObjectId() 重新声明它们,因为它们已经存在于数据库中:/我的意思是我想更新该数据......你明白我的意思吗?我能做些什么??有什么解决办法吗?
-
好的,我考虑了你在incomeSchema 中的键。您需要保持相同的格式还是灵活使用格式?
-
在检索要更新的数据时,我需要为对象 ID 保持相同的格式
-
这不是问题。问题在于incomeSchema 数组中的对象。您将键指定为动态值。 '2021-02-01income', '2021-03-01income', .... 你不能有一个动态的命名键。
标签: javascript node.js mongoose mongoose-schema mongoose-models