node.js - 在 Node 中存储 mongoDB 的收集结果

标签 node.js mongodb express database

我是 Node 新手,我已成功从 mongoDB 读取数据。

但是我想将 Collection 中的全部数据存储到 NodeJS 中的变量中,因为我想在索引页面中使用它们。

我不知道如何存储它。

// 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"
}

我想访问所有字段并根据我存储的字段创建一个页面。我需要进入所有领域,这是我的主要目标。

这是一个我喜欢的项目,我正在利用闲暇时间学习一下 MEAN 堆栈。

非常感谢您的帮助!!!!

最佳答案

此代码存在一些问题,但我认为您正在寻找的是 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);
  }
}

更多信息请参见:https://docs.mongodb.org/manual/reference/method/cursor.toArray/

这里:https://mongodb.github.io/node-mongodb-native/api-generated/cursor.html#toarray

关于node.js - 在 Node 中存储 mongoDB 的收集结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36185607/

相关文章:

node.js - 当我们在nodejs中使用mongoose从mongodb中选择复杂对象时,有什么方法可以重命名路径吗?

javascript - 加载 View 后express.js传递变量

Node.js + Express 仅在测试服务器上的端口 3000 上工作

node.js - 插入到 mongo 数组中没有发生?

javascript - 如何使用 javascript Promises 更新 mongodb 中的多个文档?

javascript - 将数据附加/插入到 MongoDB 中

node.js - mongoose/mongodb 流与数组性能

javascript - Nodejs MySQL 循环中的多个查询

javascript - 如何继承 "constructor returns another object"对象

php - DynamoDB 到 MongoDB 迁移