node.js - mongoose - how do I get the elements removed from $pull -
i'm using $pull pull subdocument within array of document. don't know if matters in case subdocuments contain _id indexed. here jsons describes schemas:
user: { _id: string, items: [useritem] } useritem: { _id: string, score: number }
now problem this: using $pull remove useritem's user.
var delta = {$pull:{}}; delta.$pull.items={}; delta.$pull.items._id = {$in: ["mongoid1", "mongoid2" ...]}; user.findoneandupdate(query, delta, {multi: true}, function(err, data){ //whatever... });
what in info here user object after change, when wish items removed array (satellite data). can done 1 phone call mongo or have 2 calls: 1 find , 1 $pull? help.
you cannot this, or @ to the lowest degree there nil going homecoming "actual" elements "pulled" array in response, newer writeresponse objects available newer mass operations api ( kind of way forwards ).
the way can "knowing" elements "intending" "pull", , comparing "original" state of document before modified. basic mongodb .findandmodify()
method allows this, mongoose wrappers of .findbyidandupdate()
, .findoneandupdate()
.
basic usage premise:
var removing = [ "mongoid1", "mongoid2" ]; model.findoneandupdate( query, { "$pull": { "items._id": { "$in": removing } } }, { "new": false }, function(err,doc) { var removed = doc.items.filter(function(item) { homecoming removing.indexof(item) != -1; }); if ( removed.length > 0 ) console.log(removed); } );
or along lines. "turn around" default mongoose .findoneandupdate()
( same other methods ) behavior , inquire "original" document before modified. if elements asked "pull" nowadays in array study them, or inspect / homecoming true or whatever.
so mongoose methods differ reference implementation returning "new" document default. turn off, , can "compare".
further notes: "multi" not valid alternative here. method modifies "one" document definition. create statement array sub-documents conatain _id
. done "mongoose" default. _id
values in array "not indexed" unless define index on field. default index "primary document" _id
.
node.js mongodb mongoose
No comments:
Post a Comment