Node.js 在节点中存储来自mongoDB的收集结果
我是node的新手,我已经成功地从mongoDB读取了数据 但是我希望将集合中的所有数据存储到nodejs中的一个变量中,因为我希望在索引页面中使用它们 我不知道如何储存它Node.js 在节点中存储来自mongoDB的收集结果,node.js,mongodb,express,database,Node.js,Mongodb,Express,Database,我是node的新手,我已经成功地从mongoDB读取了数据 但是我希望将集合中的所有数据存储到nodejs中的一个变量中,因为我希望在索引页面中使用它们 我不知道如何储存它 // Connection URL var url = 'mongodb://localhost:27017/test'; // Use connect method to connect to the Server MongoClient.connect(url, function (err, db) { as
// Connection URL
var url = 'mongodb://localhost:27017/test';
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
seriescollection = db.collection('series');
});
var findseries = function (db, callback) {
var cursor = db.collection('series').find();
cursor.each(function (err, doc) {
assert.equal(err, null);
if (doc != null) {
console.dir(doc);
} else {
callback();
}
});
};
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
//insertDocument(db, function () {});
findseries(db, function () {
db.close();
});
});
MongoDb中的示例JSON对象是
{
"_id" : "b835225ba18",
"title" : "Name",
"imageurl" :"https://promotions.bellaliant.net/files/Images/TMN/Ballers-June2015.jpg",
"namespaceId" : "UNI890"
}
我想访问所有字段,并根据存储的字段创建一个页面。我需要访问所有字段,这是我的主要目标
这是一个宠物项目,我在业余时间学习一点
非常感谢你的帮助 此代码存在一些问题,但我认为您需要的是
toArray
方法:
var findseries = function (db, callback) {
db.collection('series').find().toArray(function(err, allTheThings) {
// Do whatever with the array
// Spit them all out to console
console.log(allTheThings);
// Get the first one
allTheThings[0];
// Iterate over them
allTheThings.forEach(function(thing) {
// This is a single instance of thing
thing;
});
// Return them
callback(null, allTheThings);
}
}
详情如下:
这里:谢谢你的帮助。我得到了所有的东西作为[对象]…不是一个完整的arrayOh gezz,我太傻了。这可能是一个承诺或什么的。您需要一个回调,如下所述:我已经更新了我的代码。谢谢!!很好,我有个打字错误<代码>forEach非
forEach
。这就是问题所在吗?