Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose - ObjectID as key?

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.

like image 749
k6pib6r6 Avatar asked Nov 18 '22 02:11

k6pib6r6


1 Answers

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": ""}}
)
like image 71
shivshankar Avatar answered Dec 25 '22 23:12

shivshankar