node.js在mongodb中获得查找结果 [英] nodejs get find results in mongodb

查看:157
本文介绍了node.js在mongodb中获得查找结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取查询结果,但在所有var中都得到了相同的信息:db,collection和res:

I'm trying to get the result of query but i get the same info in all vars: db, collection and res:

var mongodb = require("mongodb");
var mongoserver = new mongodb.Server("localhost", 27017);
var instance = new mongodb.Db("test", mongoserver);

instance.open(function(err, db)
{
  console.log('db:');
  console.log(db);
  db.collection('kurtsoa', function(err, collection)
  {
    console.log('collection:');
    console.log(collection);
    collection.find({}, function(err, res)
    {
      console.log('res:');
      console.log(res);
    });
  });
});

我如何获得查找"的结果?

how i can get the result of "find"?

推荐答案

.find() 将返回一个 Cursor 对象供您使用.如果您感兴趣的是将所有结果都存储在数组中,则可以执行以下操作:

.find() will return a Cursor object for you to work with. If all you are interested in is getting all the results in an array you can do:

collection.find().toArray(function(err, docs) {
    console.log(docs);
});

但是您也可以迭代光标:

But you can also iterate the cursor too:

collection.find().each(function(err, doc) {
    //called once for each doc returned
});

这篇关于node.js在mongodb中获得查找结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆