Alaksandar Jesus Gene
Alaksandar Jesus Gene

Reputation: 6887

Fetch document by _id in express and mongodb

I am trying to create a todo list, where i am using mlab as my db provider.

tasks = db.connect().collection('tasks');
tasks.find().toArray(function (err, result) {
            console.log("result", result) // giving me result
            if(err) throw err;
             res.render('tasks/index', {title:"Tasks",tasks:result});
         })

Attached is one single shot of all routes output in console.enter image description here

In the image (1) is the output of find().toArray()

(2) is get update and i am getting the id of task in the url route params.

(3) is after i run this findOne statment.

update function -> get task based on id

tasks.findOne({"_id":"59c91fbb4b262004f059f67f"}, function(err, task){
        console.log(err)
        console.log(task)
        res.render('tasks/update', {title:"Update"});
    });

I am getting null as value.(Note: I am hard coding the value for confirmation).

Let me know why i am getting null as the id matches (which you can refer from 1).

Task-2

Also, if i want to update, how shuld i send the altered values.

Upvotes: 0

Views: 709

Answers (1)

Nicolas Ducom
Nicolas Ducom

Reputation: 248

Regarding your first question, when matching on _id with Mongo you need to define your search criteria as an ObjectId :

tasks.findOne({"_id":ObjectId("59c91fbb4b262004f059f67f")}, function(err, task){
        console.log(err)
        console.log(task)
        res.render('tasks/update', {title:"Update"});
    });

Regarding the update, are you having some kind of trouble in particular ? The documentation has plenty of information regarding the structure of the query you're supposed to send :)

Upvotes: 4

Related Questions