Ben Muircroft
Ben Muircroft

Reputation: 3034

nodejs mongodb find modify and return new. Can't canonicalize query

My question is related to this

findAndModify Error in mongodb - nodejs - error code 17287

But the solution hasn't worked (i tried specify the order but i get the same error) I think it might be something along the lines of the index I am using example instead of _id (_id is a field in this collection I just don't want to search by _id in this case) not sure at all...

The Error:

{ [MongoError: exception: nextSafe(): { $err: "Can't canonicalize query: BadValue bad sort specification", code: 17287 }]
  name: 'MongoError',
  message: 'exception: nextSafe(): { $err: "Can\'t canonicalize query: BadValue bad sort specification", code: 17287 }',
  errmsg: 'exception: nextSafe(): { $err: "Can\'t canonicalize query: BadValue bad sort specification", code: 17287 }',
  code: 13106,
  ok: 0 }

This is my code, it should find and modify (and return using new:true) the first instance of a document that has the field example equal to minus one.

db.collection('documents').findAndModify({example:-1},{$set:{example:0}},{new:true},function(err,result){
    console.dir(err||result);
    });

But all it does is error like it hates my face!

Here is a document:

{'_id':0,'example':-1}

My id field is custom numerical Where I ensure the _id is always unique (For my purposes I cannot change the _id to standard mongodb way.)

Upvotes: 2

Views: 3059

Answers (2)

Ben Muircroft
Ben Muircroft

Reputation: 3034

It was painful to get this to work as the node docs end abruptly and then you are left guessing on how the code structure should be on what would/could of just been a standard structure but isn't! I have wasted a day thanks to the devs undocumented methods.

Here is the working code

db.collection('documents').findAndModify({'example':{$eq:-1}},[['example',1]],{$set:{'example':-1}},{'new':true},function(err,result){
    console.dir(err||result);
    });

I am not sure I really like writing code like this ether. I might look for another node module for this as the query above looks disgusting!

Would be greate if I could find something that looks as simple as this:

db.collection('documents').findModifyReturn('find:example==-1;order:asc;set:example=0;',function(e,r){});

Upvotes: 2

ZeMoon
ZeMoon

Reputation: 20274

Try using the $eq operator.

db.collection('documents').findAndModify({example: {$eq: -1}}, {'example', 'ascending'},{$set:{example:0}},{new:true},function(err,result){
    console.dir(err||result);
    });

Upvotes: 0

Related Questions