Hey all, I am pretty new to mongodb but I wanted to use it for my first mern stack project. I am using mongoose with nodejs. I currently have 3 schema’s, Year at the topmost level, then a year has a subdocument array of 12months, and then each month has a reference to an envelope.
const yearSchema = new mongoose.Schema({
year: {
type: Number,
required: true,
unique: true,
},
budgetTotal: {
type: Number,
default: 0,
},
months: [month.schema],
});
const monthSchema = new mongoose.Schema({
month: {
required: true,
type: String,
},
total: {
default: 0,
type: Number
},
envelopes: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Envelope",
}],
});
const envelopeSchema = new mongoose.Schema({
month: {
type: mongoose.Schema.Types.ObjectId,
ref: "Month",
required: true,
},
category: {
required: true,
type: String
},
budget: {
required: true,
type: Number
}
});
I am struggling to work with the data. I can do get requests easy enough to find the document from a specific year. I can also post a new year and delete the whole year. What I can’t figure out how to do is modify the embedded elements. I’ve spent this morning trying to get a year then update the total parameter for each value in the month. This doesn’t work,
const data = await Year.updateMany({ year: Number(req.params.year) }, { $inc: { "months.$.total": 500 } });
my error from it was
"message": "The positional operator did not find the match needed from the query."
I also don’t understand how I would create a new envelope and make sure it’s associated with the month. I would appreciate any tips/pointers to working with data like this. I really want to get a better understanding of working with mongo