Removing an object from an array inside a Collection

时光总嘲笑我的痴心妄想 提交于 2019-12-23 01:44:18

问题


I'm using the following methods to push and pull objects into the "following" array, which is a property on each user's profile.

Meteor.users.update({ _id: this.userId }, { $push: { 
  "profile.following": { _id: _id, service: service, type: type }}
 });

// I specify that it is required to match these two properties to remove an object
Meteor.users.update({ _id: this.userId }, { $pull: { 
  "profile.following": { service: service, type: type } }
});

This approach does work, it removes the object, but I always get this error:

Exception while simulating the effect of invoking 'unfollow' Error: documentMatches needs a document {stack: (...), message: "documentMatches needs a document"} Error: documentMatches needs a document
at Error (native)
at _.extend.documentMatches (http://localhost:3000/packages/minimongo.js?e8806aa7782b729b2517ebc0cd10b321667f1427:1341:13)
at MODIFIERS.$pull (http://localhost:3000/packages/minimongo.js?e8806aa7782b729b2517ebc0cd10b321667f1427:3414:24)
at http://localhost:3000/packages/minimongo.js?e8806aa7782b729b2517ebc0cd10b321667f1427:3124:9
at Function._.each._.forEach (http://localhost:3000/packages/underscore.js?0a80a8623e1b40b5df5a05582f288ddd586eaa18:164:22)
at http://localhost:3000/packages/minimongo.js?e8806aa7782b729b2517ebc0cd10b321667f1427:3105:9
at Function._.each._.forEach (http://localhost:3000/packages/underscore.js?0a80a8623e1b40b5df5a05582f288ddd586eaa18:164:22)
at Function.LocalCollection._modify (http://localhost:3000/packages/minimongo.js?e8806aa7782b729b2517ebc0cd10b321667f1427:3098:7)
at LocalCollection._modifyAndNotify (http://localhost:3000/packages/minimongo.js?e8806aa7782b729b2517ebc0cd10b321667f1427:848:19)
at http://localhost:3000/packages/minimongo.js?e8806aa7782b729b2517ebc0cd10b321667f1427:765:12

I'm not sure if this is a bug with Meteor or if I maybe I'm not writing the query correctly.


回答1:


Apparent $elemMatch is needed to do this:

Meteor.users.update({ _id: this.userId }, { $pull: { 
  "profile.following": { $elemMatch: { service: service, type: type } } }
});


来源:https://stackoverflow.com/questions/28948990/removing-an-object-from-an-array-inside-a-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!