Search code examples
node.jsmongodbnpmmongoose

Mongoose.Model.findById() return null


const mongoose =  require('mongoose');
mongoose.connect('mongodb://localhost/mongo-exercises')
        .then(()=>{
            console.log('DataBase Connected..!!');
        })
        .catch(err=> console.log('Connection err: ',err));
const schema = new mongoose.Schema({
    tags:[ String ],
    date:Date,
    name: String,
    author: String,
    isPublished: Boolean,
    price: Number
});
const Course = mongoose.model('course',schema);
async function updateCourse(id){
    const course = await Course.findById(id);
    if(!course) return;
    course.name = "mongo db";
    console.log(course)
    const result = await course.save();
}

updateCourse("5a68fdc3615eda645bc6bdec");      

My updateCourse(id) is returning null. output::

C:\Users\Divay Mohan\Desktop\100DaysOfCode\Day9\PracticeCRUD>node index.js
DataBase Connected..!!
  mquery findOne courses { _id: 5a68fdc3615eda645bc6bdec } { fields: {} } +0ms

And with same program::

const mongoose =  require('mongoose');

mongoose.connect('mongodb://localhost/mongo-exercises')
        .then(()=>console.log('DataBase Connected..!!'))
        .catch(err=> console.log('Connection err: ',err));

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

const Course = mongoose.model('course',schema);
async function getCourses(){
    const result =  await Course.find();
    console.log(result);
}
getCourses();

Output:

C:\Users\Divay Mohan\Desktop\100DaysOfCode\Day9\PracticeCRUD>node exercise3.js
DataBase Connected..!!
[ { tags: [ 'react', 'frontend' ],
    _id: 5a68fdf95db93f6477053ddd,
    date: 2018-01-24T21:43:21.589Z,
    name: 'React Course',
    author: 'Parbhu',
    isPublished: false,
    __v: 0 },
  { tags: [ 'express', 'backend' ],
    _id: 5a68fdc3615eda645bc6bdec,
    date: 2018-01-24T21:42:27.388Z,
    name: 'Express.js Course',
    author: 'DM',
    isPublished: true,
    price: 10,
    __v: 0 },
  { tags: [ 'aspnet', 'backend' ],
    _id: 5a68fde3f09ad7646ddec17e,
    date: 2018-01-24T21:42:59.605Z,
    name: 'ASP.NET MVC Course',
    author: 'Divay',
    isPublished: true,
    price: 15,
    __v: 0 },
  { tags: [ 'node', 'backend' ],
    _id: 5a68ff090c553064a218a547,
    date: 2018-01-24T21:47:53.128Z,
    name: 'Node.js Course by Mohan',
    author: 'Mohan',
    isPublished: false,
    price: 12,
    __v: 0 },
  { tags: [ 'angular', 'frontend' ],
    _id: 5a6900fff467be65019a9001,
    date: 2018-01-24T21:56:15.353Z,
    name: 'Angular Course',
    author: 'kate',
    isPublished: true,
    price: 15,
    __v: 0 },
  { tags: [ 'node', 'backend' ],
    _id: 5a68fdd7bee8ea64649c2777,
    date: 2018-01-24T21:42:47.912Z,
    name: 'Node.js Course',
    author: 'Tom',
    isPublished: true,
    price: 20,
    __v: 0 },
  { tags: [ 'node', 'backend' ],
    _id: 5a68fe2142ae6a6482c4c9cb,
    date: 2018-01-24T21:44:01.075Z,
    name: 'Node.js Course by More',
    author: 'More',
    isPublished: true,
    price: 12,
    __v: 0 } ]

Compare Both Programs and output . first one with Model.find() is working fine but Model.findById() is not working. Here is the Configuration on which i am working right now:

{
  "name": "PracticeCRUD",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "mongoose": "^5.0.1"
  }
}

and

  1. npm version is 5.5.1
  2. node verson is 8.9.4
  3. MongoDB version is MongoDB 4.2.6 Community

Please Help me with that. Thank You..


Solution

  • Since you haven't specified the type of _id in your schema it will default to type ObjectId. So for findById to work the value of the _id in the database should be also of type ObjectId. In your case, if you list the documents in mongo shell _id should be something like "_id" : ObjectId("5a68fdc3615eda645bc6bdec")

    Can you try creating a record from you code and try to query it

    let c = new Course({ "tags": [ 'express', 'backend' ],     date: "2018-01-24T21:42:27.388Z",     "name": 'Express.js Course',     "author": 'Mosh',     "isPublished": true,     "price": 10})
    c.save((err, result) => {
        if (err) console.log(err);
        console.log("new record added: " + result);
      });