Mongoose findbyid() return null

前端 未结 5 828
时光取名叫无心
时光取名叫无心 2021-01-13 01:04

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?

相关标签:
5条回答
  • 2021-01-13 01:21

    Convert the string into ObjectId type before querying

    var ObjectID = require('mongodb').ObjectID;   
    async function updateData(id){
      const result = await Data.findById(new ObjectID(id));
      console.log(result);
    }
    

    refer: this answer.

    0 讨论(0)
  • 2021-01-13 01:25

    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.

    0 讨论(0)
  • 2021-01-13 01:34

    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

    0 讨论(0)
  • 2021-01-13 01:37

    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,
    ...
    ...
    }
    
    0 讨论(0)
  • 2021-01-13 01:41

    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 讨论(0)
提交回复
热议问题