1
db.collection('test').find({"title":"I like cake"}/*,{projection:{_id:true}}*/).toArray(function(err, results){
            if(err) throw err;

            id = "5b7fb08f823d6137e08a7d8a";
        });

        db.collection('test').findOne({_id: new ObjectId(id)}, function(err, results){
            if(err) throw err;  
            console.log(results);
        });

it' not work. (return null) following example is work.

db.collection('test').find({"title":"I like cake"}/*,{projection:{_id:true}}*/).toArray(function(err, results){
            if(err) throw err;

        });

        db.collection('test').findOne({_id: new ObjectId("5b7fb08f823d6137e08a7d8a")}, function(err, results){
            if(err) throw err;  
            console.log(results);
        });

What's the difference? How do i fix it?

김동환
  • 9
  • 6

2 Answers2

1

The real issue is that you are setting the ID in a callback function which is asynchronous. Thus, when the findOne query executes, the ID is not yet set.

You might want to move the second query inside the callback function itself:

db.collection("test")
  .find({ title: "I like cake" } /*,{projection:{_id:true}}*/)
  .toArray(function(err, results) {
    if (err) throw err;

    var id = "5b7fb08f823d6137e08a7d8a";

    db.collection("test").findOne({ _id: new ObjectId(id) }, function(err,results) {
      if (err) throw err;
      console.log(results);
    });
  });
Anand Undavia
  • 3,493
  • 5
  • 19
  • 33
1

Try this code

 db.collection("test").find({}).toArray(function(err, result) {
   db.collection("test").find({
     _id:new ObjectID('5b7fb08f823d6137e08a7d8a')
     }).toArray(function(err, result) {
     if (err) throw err;
     console.log(JSON.stringify(result,undefined,2));
     //db.close();
   });
 });
Prashant Gupta
  • 788
  • 8
  • 26