Mongoose - ObjectID as a key?

I would like to have an object (the “ingredients” in the example) in my mongoose model, where the keys are ObjectID and their values ​​are numbers. Can this be done? How to determine my mongoose pattern? You can find an example below.

JSON example:

  {
    "_id": ""5a2539b41c574006c46f1a07",
    "name": "xyz",
    "ingredients": {
        "5a23f5e6159f5c3438c75971": 50,
        "5a23f60b159f5c3438c75972": 50,
        "5a255b04c9d9c40ac8927dd5": 50
    }
  }

Thank you for your help.

+4
source share
2 answers

you can use a mixing scheme

{
    "_id": ""5a2539b41c574006c46f1a07",
    "name": "xyz",
    "ingredients": mongoose.Schema.Types.mix
  }

link way to create dynamic document keys in mongodb

Dynamic key insertion is so easy

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 that you will also need to update the dymanic key in the future to take the link Update the Mongo array: delete the dynamic key

collection.update(
    {"_id": ObjectId("5a2539b41c574006c46f1a07")},
    {"$unset": {"ingredients.5a23f5e6159f5c3438c75971": ""}}
)
+1
source

In the model file:

(...)
ingredients: {
    id: { type: mongoose.Schema.ObjectId, ref: 'xxx' } ,
    value: Number,
  },
(...)
Run codeHide result

xxx .

+1

Source: https://habr.com/ru/post/1690348/


All Articles