简体   繁体   中英

Node MongoDB driver: can't findOne by integer id with the driver but can with mongo shell

I have problems querying a document by id with findOne() . The documents are written to shorts collection with a custom automatically incremented integer id. The resulting documents have format as eg { "_id": 13, "fullURL": "google.com" } . When I'm trying to query a document from the collection it returns null :

 // call queryUrlById(db, 13) const queryUrlById = (db, id) => { console.log(`searching id: ${id}`); return new Promise((resolve, reject) => { db.collection('shorts') .findOne({ _id: id }) .then(found => { console.log(`Found: ${found}`); db.close(); resolve(found.fullURL); }) .catch(err => { db.close(); reject(err); }) }); }; // In console: // searching id: 13 // Found: null 

At the same time, an identical command in mongo shell works just fine:

> db.shorts.findOne({_id: 13})
{ "_id" : 13, "fullURL" : "google.com" }

What I've tried so far:

  1. Rewrite findOne() with a callback
  2. Change the query to {"_id": id}

None of which worked out as expected.

If you mongodb package installed,you can run the query using the below 2 lines

var mongo=require("mongodb").MongoClient;
var ObjectID=require("mongodb").ObjectId;

The syntax of the findOne function should be as follows:

db.collection("shorts").findOne({_id:ObjectID(id)});

The id in the query required casting from String to Number.

@str was first to post the solution. Thanks to everyone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM