MongoDB findByID不起作用,但找到ALL工作

时间:2016-02-19 07:24:12

标签: node.js mongodb-query

我尝试使用node,js在mongodb上创建一个CRUD api 我现在可以使用find all,以某种方式坚持,findByID不起作用 我关注this onethis one,它只是不起作用,请帮助

代码

exports.findAll = function(req, res) {
db.collection('songs',function(err, collection) {
collection.find().toArray(function(err, items) {
  res.send(items);
});
});\\\this one works
};

   var id = req.params.id;
   console.log('Retrieving song: ' + id);
   db.collection('songs', function(err, collection) {
   collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
  res.send(item);
  });
});
};
\\this one not work

错误

c:\Users\awei\WebstormProjects\untitled\routes\girlshanlder.js:23
db.collection.findOne('_id',function(err, collection) {
            ^

TypeError: Cannot read property 'findOne' of undefined
   at c:\Users\awei\WebstormProjects\untitled\routes\girlshanlder.js:27:15
   at Db.collection (c:\Users\awei\node_modules\mongoose\node_modules\mongodb\lib\db.js:445:27)
   at exports.findById (c:\Users\awei\WebstormProjects\untitled\routes\girlshanlder.js:26:6)
   at Layer.handle [as handle_request] (c:\Users\awei\node_modules\express\lib\router\layer.js:95:5)
   at next (c:\Users\awei\node_modules\express\lib\router\route.js:131:13)
   at Route.dispatch (c:\Users\awei\node_modules\express\lib\router\route.js:112:3)
   at Layer.handle [as handle_request] (c:\Users\awei\node_modules\express\lib\router\layer.js:95:5)
   at c:\Users\awei\node_modules\express\lib\router\index.js:277:22
   at param (c:\Users\awei\node_modules\express\lib\router\index.js:349:14)
   at param (c:\Users\awei\node_modules\express\lib\router\index.js:365:14)
   at Function.process_params (c:\Users\awei\node_modules\express\lib\router\index.js:410:3)
   at next (c:\Users\awei\node_modules\express\lib\router\index.js:271:10)
   at expressInit (c:\Users\awei\node_modules\express\lib\middleware\init.js:33:5)
   at Layer.handle [as handle_request] (c:\Users\awei\node_modules\express\lib\router\layer.js:95:5)
   at trim_prefix (c:\Users\awei\node_modules\express\lib\router\index.js:312:13)
   at c:\Users\awei\node_modules\express\lib\router\index.js:280:7

2 个答案:

答案 0 :(得分:1)

试试这个

db.collection('songs', function(err, collection) {
   collection.findOne({_id: `someId`}, function(err, items) {
       res.send(items);

答案 1 :(得分:0)

好的,我找到了答案,这就是工作!

  

var BSON = require('bson')。BSONPure