Brian Gwaltney
Brian Gwaltney

Reputation: 419

Mongoose findbyid / find({id: "..."}) returning Null

I have seen this asked several times, but I haven't found a solution that has worked. I am trying to query a MongoDB using Mongoose .findById and am not getting the expected results. find({id: "..."}) is also not returning anything.

Using find without any parameters displays all of the expected results including id key-value pairs, but I cannot use the id value in the query.

Using mongoose: 5.4.9

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/mongo-exercises', { useNewUrlParser: true });

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

const Course = mongoose.model('Course', courseSchema);

async function getCourses() {
  return await Course
    .find()
}

async function run() {
  const result = await getCourses();
  console.log(result);
}
run();
//Return
    [ { tags: [ 'react', 'frontend' ],
    _id: 5a68fdf95db93f6477053ddd,
    date: 2018-01-24T21:43:21.589Z,
    name: 'React Course',
    author: 'Mosh',
    isPublished: false,
    __v: 0 },
  { tags: [ 'aspnet', 'backend' ],
    _id: 5a68fde3f09ad7646ddec17e,
    date: 2018-01-24T21:42:59.605Z,
    name: 'ASP.NET MVC Course',
    author: 'Mosh',
    isPublished: true,
    price: 15,
    __v: 0 },
  { tags: [ 'node', 'backend' ],
    _id: 5a68fe2142ae6a6482c4c9cb,
    date: 2018-01-24T21:44:01.075Z,
    name: 'Node.js Course by Jack',
    author: 'Jack',
    isPublished: true,
    price: 12,
    __v: 0 },
  { tags: [ 'node', 'backend' ],
    _id: 5a68fdd7bee8ea64649c2777,
    date: 2018-01-24T21:42:47.912Z,
    name: 'Node.js Course',
    author: 'Mosh',
    isPublished: true,
    price: 20,
    __v: 0 },
  { tags: [ 'node', 'backend' ],
    _id: 5a68ff090c553064a218a547,
    date: 2018-01-24T21:47:53.128Z,
    name: 'Node.js Course by Mary',
    author: 'Mary',
    isPublished: false,
    price: 12,
    __v: 0 },
  { tags: [ 'angular', 'frontend' ],
    _id: 5a6900fff467be65019a9001,
    date: 2018-01-24T21:56:15.353Z,
    name: 'Angular Course',
    author: 'Mosh',
    isPublished: true,
    price: 15,
    __v: 0 },
  { tags: [ 'express', 'backend' ],
    _id: 5a68fdc3615eda645bc6bdec,
    date: 2018-01-24T21:42:27.388Z,
    name: 'Express.js Course',
    author: 'Mosh',
    isPublished: true,
    price: 10,
    __v: 0 } ]

That code verifies I'm connected to the correct database and retrieving real ids. When I modify the getCourses function as shown below, I get null or an empty array depending on whether I use findById or find({id: "..."}).

async function getCourses() {
  return await Course
    .findById('5a68fdf95db93f6477053ddd')
}
//null

async function getCourses() {
  return await Course
    .find({ id: '5a68fdf95db93f6477053ddd' })
}
// []

async function getCourses() {
  return await Course
    .find({ _id: '5a68fdf95db93f6477053ddd' })
}
// []

Any help would be greatly appreciated. Thank you!

EDIT: Showing full find() response.

Upvotes: 0

Views: 2181

Answers (1)

Şivā SankĂr
Şivā SankĂr

Reputation: 2036

Upon our discussion as your importing the data from JSON file, So its inserting the _id as string, While finding the document by _id, moognoose automatically converting string to Object.

// Original JSON
{
    "_id": "5a68fde3f09ad7646ddec17e",
    "tags": [
        "aspnet",
        "backend"
    ],
    "date": "2018-01-24T21:42:59.605Z",
    "name": "ASP.NET MVC Course",
    "author": "Mosh",
    "isPublished": true,
    "price": 15,
    "__v": 0
}

Solution 1 :

To insert the _id as in the JSON, change your _id field with $oid as below,

{
    "_id": { "$oid": "5a68fde3f09ad7646ddec17e" },
    "tags": [
        "aspnet",
        "backend"
    ],
    "date": "2018-01-24T21:42:59.605Z",
    "name": "ASP.NET MVC Course",
    "author": "Mosh",
    "isPublished": true,
    "price": 15,
    "__v": 0
}

Solution 2 :

Remove _id from your JSON, MongoDB will generate a _id automatically

{
    "tags": [
        "aspnet",
        "backend"
    ],
    "date": "2018-01-24T21:42:59.605Z",
    "name": "ASP.NET MVC Course",
    "author": "Mosh",
    "isPublished": true,
    "price": 15,
    "__v": 0
}

Upvotes: 1

Related Questions