Node.js driver "mongodb" implementation of findAndModify() - how to specify fields?

415 views
Skip to first unread message

Samir Said

unread,
Jun 6, 2014, 10:28:26 PM6/6/14
to node-mong...@googlegroups.com, Steven Shaginyan
Hi,

I'm trying to pop and retrieve an element out of an array stored in a document. I can't use $pop since it doesn't return the POPed element. I'm trying to use findAndModify() instead. It works in the shell console, but I'm having troubles getting it to work using the mongodb node.js driver (https://www.npmjs.org/package/mongodb).


my document structure looks like so: { _id: '1', queue: [1,2,3]}

In mongo shell, I do:
> db.collection.findAndModify({ query: { _id: 1 }, update: { $pop: { queue: -1 } }, fields: { queue: { $slice: 1 } }, new: false })   //$slice ensures that the returning document shows the element that has just been poped. To clarify, I'm not interested in what is in the queue, I'm only interested in what I have just popped out of the queue.

returns:
< {_id: 1, "queue": [1]} // yes, it works! 


Using the mongodb library, I don't know how to specify the $slice: 1, it doesn't seem to be supported in the options(?):
> db.collection('collection').findAndModify({ _id: 1 }, [], { $pop: { queue: -1 }, queue: { $slice: 1 } }, { new: false }, function(error, results) {
        if(error) {
            console.log(error);
        }
        console.log(results);
    });

returns:
< MongoError: exception: Field name duplication not allowed with modifiers



Basically - where should I put the "queue: {$slice: 1}" part in the nodejs query to make this work? Is it even supported in the node.js driver implementation? Also, it doesn't seem like findAndModify() is meant to be used this way. If $pop was returning the POPed value, it would be ideal. Any suggestions on how to do this?

Thanks, 
 - Samir

Vladimir Kurijov

unread,
Sep 22, 2014, 3:42:42 AM9/22/14
to node-mong...@googlegroups.com, sshag...@gmail.com
I'm searching for the same options, did you find the answer?

суббота, 7 июня 2014 г., 6:28:26 UTC+4 пользователь Samir Said написал:

Vladimir Kurijov

unread,
Sep 22, 2014, 3:50:33 AM9/22/14
to node-mong...@googlegroups.com, sshag...@gmail.com
That was easy one, I found the answer. Options object accepts `fields` key, that is missing in the docs, but you can easily find it in the source code.

понедельник, 22 сентября 2014 г., 11:42:42 UTC+4 пользователь Vladimir Kurijov написал:
Reply all
Reply to author
Forward
0 new messages