1

I'm trying to add a field to a logs field that will gain it's name dynamically. E.g if I want to push an update about the field "Name" I'd want to be able to decide at runtime that it should be named so. I'm going to try my best to explain below.

How my data should look is this. Notice the tree: logs.(dynamicName).{ts, prop, value}. The dynamicName is inherited from the prop value.

"logs": {
    "Name": [
      {
        "ts": 1436952585736,
        "prop": "Name",
        "value": "Fredd"
      },
      {
        "ts": 1436952600336,
        "prop": "Name",
        "value": "Fred"
      }
    ],
    "description": [
      {
        "ts": 1436952585736,
        "prop": "description",
        "value": "A normal bloke"
      }
    ],

The data I receive in my application is shaped like this:

      {
        "prop": "description",
        "value": "A normal bloke"
      }

I'm stumped. I simply want to $push to a new array with a dynamic name, e.g. like this:

var logName = "logs."+prop;
collection.update(
    {_id: documentId},
    { $push:
      { logName:
        {
          "ts": Date.now(),
          "prop": log.prop,
          "value": log.value
        }
      }
    }

But of course this cannot simply be: Mongo (or perhaps the node.js driver) takes the variable logName literally. And I really want to keep this data format instead of just having a singular logs array.

1 Answer 1

3

With JavaScript, you use the "bracket" [] notation in order to use a variable in part of an object key.

// Input things
var prop = "Name";
var payload = {
    "prop": "description",
    "value": "A normal bloke"
};

// Manipulation code
payload.ts = new Date();
var update = { "$push": {} };
update["$push"]["logs." + logName] = payload;

And that basically comes out like:

{ "$push": { "logs.Name": { "prop": "description", "value": "A normal bloke" } } }

So then you just do:

collection.update({ "_id": documentId },update);

As the update object for your statement has been contructed with the key name set using a variable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.