简体   繁体   English

Express.js collection.find()返回对象

[英]Express.js collection.find() return Object

I am wanted to display every documents stored in my mongodb. 我想显示存储在mongodb中的每个文档。 I tried following code which simply get collection.find() and display through res.send() 我尝试了以下代码,这些代码仅获取collection.find()并通过res.send()显示

router.get('/index', function(req,res){
var db = req.db
var collection = db.get('usercollection')

var display = util.inspect(collection.find()));
res.send(display);
});

I expected it to display the actual document stored in mongodb. 我希望它能显示存储在mongodb中的实际文档。 But instead, it displayed this object format: 但是,它显示了这种对象格式:

{cold:{manager:{driver:[Object], helper:[Object], collection:[Object].....

Is there any other steps needed to display raw mongodb document? 显示原始的mongodb文档是否还需要其他步骤?

If the library you are using is the official 10gen library , then you can't simply output collection.find() without unwinding it. 如果您使用的库是官方的10gen库 ,那么您不能简单地输出collection.find()而不将其展开。 The easiest way to do that for smaller datasets is 对于较小的数据集,最简单的方法是

collection.find().toArray(function(err, results) {
  if (err) {
      // do something error-y
  } else {
      res.send( results );
  }
});

If you post more of your code, and tag your question with the libraries you are using, you'll be able to get more targeted help. 如果您发布更多的代码,并使用正在使用的库标记您的问题,您将可以获得更多有针对性的帮助。 If the library you are using returns a promise , this is probably how you'd unwind it: 如果您使用的库返回一个promise ,这可能是您释放它的方式:

collection.find().then(function(results){
    res.send(results);
}).catch(function(err){
    console.error(err);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM