最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Updating array element in a collection in Meteor - Stack Overflow

programmeradmin8浏览0评论

I'm trying to find and update an element within an array in a mongodb collection in a meteor app.

Every element in the array is an object that has an "_id" attribute, so I'm using mongo's '$' pointer:

Collection.update({things._id: currentThingId},{$set: {things.$.value: aGivenValue}});

However, it keeps throwing me an "Unexpected ." exception, pointing to the line where I use "things**.**_id". I followed mongodb documentation, so any chance meteor has some limitatiob with this mongo functionality?

I'm trying to find and update an element within an array in a mongodb collection in a meteor app.

Every element in the array is an object that has an "_id" attribute, so I'm using mongo's '$' pointer:

Collection.update({things._id: currentThingId},{$set: {things.$.value: aGivenValue}});

However, it keeps throwing me an "Unexpected ." exception, pointing to the line where I use "things**.**_id". I followed mongodb documentation, so any chance meteor has some limitatiob with this mongo functionality?

Share Improve this question asked May 23, 2015 at 14:53 MabooMaboo 4251 gold badge9 silver badges18 bronze badges 2
  • 1 You forgot the quotes around "things._id" and co. It has to look like {'things._id' : currentThingId}. You can't use . in a property name outside a string. – Kyll Commented May 23, 2015 at 15:25
  • You right. I tried to enclose with "" before asking here, but did forgot the things.$.value. Thanks! – Maboo Commented May 25, 2015 at 5:53
Add a ment  | 

2 Answers 2

Reset to default 4

You need to enclose the field with quotes when using the dot notation to access an element of an array by the zero-based index position, bearing in mind that the positional $ operator limits the contents of an array from the query results to contain only the first element matching the query document. Thus your final update query should look like:

Collection.update({"things._id": currentThingId},{$set: {"things.$.value": aGivenValue}});

If every element in your array is an object with an "_id" attribute, why don't you use Collection.update({_id: currentThingId},{$set:{fieldToSet: aGivenValue}}); where fieldToSet is the name of the attribute you want to set aGivenValue to.

发布评论

评论列表(0)

  1. 暂无评论