NodeJS + Mongo-如何获取集合的内容? [英] NodeJS + Mongo - how to get the contents of collection?
问题描述
我正在用mongo编写一个简单的NodeJS应用程序.要连接到mongo,我使用:
I'm writing a simple NodeJS app with mongo. For connecting to mongo I use:
var mongo = require('mongodb'),
Server = mongo.Server,
Db = mongo.Db,
ObjectID = require('mongodb').ObjectID;
db.open(function(err,db) {...};
因此,我有数据库"docs",并且创建了一个名为"companies"的集合.现在,它具有4个对象(记录).我想以数组的形式获取此集合的全部内容,并逐行显示它们:
So, I have database "docs", and I've created a collection called "companies". Now it has 4 objects (records) in it. I want to get the full contents of this collection as an array and show them line-by-line:
//get companies list
app.get('/companies',function(req,res){
db.collection("companies",function(err,collection){
collection.find({},function(err, companies) {
companies.forEach(function(err,company){
console.log (company);
}
);
});
});
});
但是,Node向我返回了这样的错误:
However, Node returns me such error:
TypeError: Object #<Cursor> has no method 'forEach'
有什么想法吗?预先感谢.
Any ideas? Thanks in advance.
推荐答案
The companies
parameter that's passed into your find
callback is a Cursor
object, not an array. Call toArray
on it to convert the query results to an array of objects, or each
to process the results one at a time.
这篇关于NodeJS + Mongo-如何获取集合的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!