12

I am trying to find a record in my mongo db by its id

No matter I use findbyid(), findone(id,...), it return null

here is my code. what is the solution?

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/Movie', {useNewUrlParser: true})
.then(() => console.log('Connected to Databse'))
.catch(err => console.err('Could not connect to MongoDB', err));

var ObjectId = require('mongodb').ObjectID;

const Schema = new mongoose.Schema({
    name: String,
    author: String,
    tags: [String],
    date: Date, 
    isPublished: Boolean,
    price: Number
});

const Data = mongoose.model('Datas', Schema);

async function updateData(id){
const result = await Data.findById(id);
console.log(result);
}
updateData('5a6900fff467be65019a9001');
Kenny
  • 226
  • 1
  • 3
  • 13
  • 1
    Silly question: are you 100% sure the record is there in the DB? – Sid Sep 03 '18 at 10:18
  • Yes, I am sure. I have use findone() by the 'name' in my database, it return sth. But not work in '_id' – Kenny Sep 03 '18 at 10:20
  • you are passing string whereas findById want objectId. Try with objectid – Prashant Tapase Sep 03 '18 at 10:25
  • @Sid is right.. You probably don't have this specific record in your db... Running the exact same code works for me.. Just add `Data.create({}).then(console.log)` and copy the returned id to your updateData function... – Ron537 Sep 03 '18 at 10:51
  • here is a funny point, The _id which is hard code inside the database, is a String type. I just realise it few second ago.Thus, findbyid always not work. Now Problem solved. Thanks everyone – Kenny Sep 03 '18 at 10:59
  • Please read my answer on this thread: https://stackoverflow.com/a/58705908/4687359 Hope find it useful. – A. Nadjar Nov 05 '19 at 07:19

7 Answers7

43

I had the same problem. The _id in my DB collection was a String. After I enabled mongoose debug require('mongoose').set('debug', true), I found out that the mongoose query id as ObjectId("yourId") unless we define _id in the Schema. In order to solve the problem I had to add _id:String in to mongoose schema.

const MyDataSchema = new Schema({
  _id: String,
...
...
}
Pramod
  • 706
  • 8
  • 8
5

There is a simple solution to this:

Replace

const result = await Data.findById(id);

with

const result = await Data.findById(id).exec();

See Mongoose - What does the exec function do? for an explanation on what exec() does

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Sylvestaro
  • 101
  • 2
  • 7
3

Check your mongodb database, if _id is storaged as String, findById(id) can not found id. FindById(id) only finds ObjectId('yourId'). You might import database by using mongoimport and including _id in JSON, it's wrong, delete _id in imported JSON.

Prashant Gupta
  • 788
  • 8
  • 26
2

After hour of searching i needed to add _id to Schema like this:

  _id: { type: Schema.Types.ObjectId },
mradex77
  • 118
  • 2
  • 8
1

I was also facing the same issue. Then I referred to this solution Make sure the documents in the collection have _id as an Object rather than a String. If you have imported the database entries using a JSON file, just remove all the _id fields and then import it.

After importing, MongoDB will itself assign the _id values to all the entries.

saurabhlahoti
  • 466
  • 8
  • 21
0

In my case, the imported file used to have the _id column as string, so it was messing the DB and I was no able to filter using that column.

Once I deleted the collection, removed the _id column from data file and re-imported it, the _id filtering started working fine.

0

I also had the same problem. It was simply solved by using findOne method instead of findById method of mongoose.

findOne syntax -

findOne({id: id-of-user},function(err,foundUser){
console.log(foundUser);
});