I would like to have an object("ingredients" in example) in my mongoose model, where the keys are ObjectIDs, and their values are numbers. Is it possible to do so? How should I define my mongoose schema? You can find an example below.
Example JSON:
{
"_id": ""5a2539b41c574006c46f1a07",
"name": "xyz",
"ingredients": {
"5a23f5e6159f5c3438c75971": 50,
"5a23f60b159f5c3438c75972": 50,
"5a255b04c9d9c40ac8927dd5": 50
}
}
Thank you for your help in advance.
you can use mix schema
{
"_id": ""5a2539b41c574006c46f1a07",
"name": "xyz",
"ingredients": mongoose.Schema.Types.mix
}
reference how to create dynamic document keys in mongodb
insertion of dynamic key is so simple
insertData_dynamic_colone: function(collection, colone1, colone2) {
var obj = {};
obj[colone1] = "14";
obj[colone2] = "15";
dbObject.collection(collection).insertOne(obj, function(err, result) {
assert.equal(err, null);
});
}
i know you'll also need to update dymanic key in future take a reference Update Mongo array: remove dynamic key
collection.update(
{"_id": ObjectId("5a2539b41c574006c46f1a07")},
{"$unset": {"ingredients.5a23f5e6159f5c3438c75971": ""}}
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With