2

I am using MongoDB with Javascript. I am trying to declare the following parameters:

params = {
  title: title,
  description: description,
  "media.image": image,
  feedUpdated: new Date()
};

Then I run a the query using a Service that includes the use of $set as follows:

collection.update({
    _id: ObjectId(id)
  }, {
    $set: {
      params
    }
  }, function(e, updated) {
    cb(e, updated);
  });

But I get the following error:

MongoError: The dotted field 'media.image' in 'params.media.image' is not valid for storage.

I think the issue is due to the fact that by declaring the object using quotes it declares it as an object key "media.image" instead of leaving it as a string. According to MongoDB $set documentation:

To specify a in an embedded document or in an array, use dot notation.

https://docs.mongodb.com/manual/reference/operator/update/set/

I could technically write manually the query to include 'media.image' but I would prefer to declare it in the params and pass it to the Service.

Any ideas? All approaches are welcome!

2
  • That's a JavaScript error. What you mean is $set: params. When you do $set: { params } it gets expanded as applying "params" as the name of the key for the object. Much the same as writing '$set': { 'params': params }, which of course you do not want. params is already an object. You don't need to wrap it in one. Commented Sep 10, 2017 at 1:31
  • Yes you're right! Thank you! Commented Sep 10, 2017 at 4:35

2 Answers 2

1

You are not allowed to use dots in keys while working with MongoDB. I can suggest two approaches:

// #1 camelCase
params = {
  title: title,
  description: description,
  mediaImage: image,
  feedUpdated: new Date()
}

// #2 object
params = {
  title: title,
  description: description,
  media: { image: image },
  feedUpdated: new Date()
}
Sign up to request clarification or add additional context in comments.

3 Comments

To specify a <field> in an embedded document or in an array, use dot notation. docs.mongodb.com/manual/reference/operator/update/set
Not the issue. What the OP is trying to do "dot notation" wise is perfectly valid. The actual problem is a misunderstanding of JavaScript syntax.
I've got it now, thanks. I thought OP is trying to update params field.
0

With JavaScript, thanks to ECMAScript 2015 computed property names, you can use dot notation by adding brackets [] around the key in question. In your case, it would be:

params = {
  title: title,
  description: description,
  ["media.image"]: image,
  feedUpdated: new Date()
};

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.