【问题标题】:How to output mongodb collections in nodejs app to get them in response如何在 nodejs 应用程序中输出 mongodb 集合以获取响应
【发布时间】:2015-07-29 13:32:40
【问题描述】:

我正在使用 Cloude 9 环境来开发我的 nodejs 应用程序。在那我已经编写了连接到 mongodb 数据库的代码。我成功连接到数据库并将记录添加到集合中。

现在我想发送收藏信息作为回报。但是使用res.send(collectionInfo); 不起作用。

让我知道我应该如何实现这一目标

下面是我的 server.js 文件的代码

var Db = require('mongodb').Db;
var http = require('http');
var path = require('path');

var async = require('async');
var socketio = require('socket.io');
var express = require('express');
var ejs = require('ejs');

var app = express();

var helpers = require('express-helpers')

var MongoClient = require('mongodb').MongoClient;
var Server = require('mongodb').Server;
var db;

helpers(app);

var bodyParser = require('body-parser');

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({extended: true})); // for parsing application/x-www-form-urlencoded
var server = http.Server(app);

server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function () {
    var addr = server.address();
    console.log("Chat server listening at", addr.address + ":" + addr.port);
});
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/public/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

//app.use(express.static(__dirname + '/client'));
app.use(express.static(path.join(__dirname, '/client')));

// MongoDB Connection
app.use(function(req, res, next) {
    next();
})

app.get('/monogdb', function (req, res) {
    res.render('monogdb.ejs');
});

app.post('/ajax-mongo-connect', function (req, res) {
    var mongoClient = new MongoClient(new Server('localhost', 27017));
    mongoClient.open(function(err, mongoClient) {
        if(err){
            console.log(err);
        }else{

            var db = mongoClient.db("mydb");
            db.createCollection("students", { name : req.body.nm, description : req.body.desc, location : req.body.loc } );
            console.log('database connected',db);
            var collectionInfo = db.collection("students");
            mongoClient.close();
            //res.setHeader('Content-Type', 'application/json');
            res.send(collectionInfo);

        }
    })
})

根据@Roman Sachenko 的回答,我尝试使用 res.send(collectionInfo.toJSON()); 但它给出以下错误

/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/db.js:299 
throw err; 
^ 
TypeError: Object #<Collection> has no method 'toJSON' 
at /home/ubuntu/workspace/server.js:66:41 
at MongoClient.open
(/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/mongo_client.js:103:5) 
 at Db.open (/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/db.js:296:11) 
 at process._tickCallback (node.js:442:13) 

使用res.send({data: collectionInfo}); 会出错

home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/db.js:299                                                                                                 
throw err;                                                                                                                                              
     ^                                                                                                                                                 
TypeError: Converting circular structure to JSON                                                                                                                  
at Object.stringify (native)                                                                                                                                  
at ServerResponse.res.json (/home/ubuntu/workspace/node_modules/express/lib/response.js:185:19)                                                               
at ServerResponse.res.send (/home/ubuntu/workspace/node_modules/express/lib/response.js:117:21)                                                               
at /home/ubuntu/workspace/server.js:67:21                                                                                                                     
at MongoClient.open (/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/mongo_client.js:103:5)                                                           
at Db.open (/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/db.js:296:11)                                                                             
at process._tickCallback (node.js:442:13)

【问题讨论】:

  • 您应该对 process.env.PORT 很好,但请注意,您只能在 Cloud9 上公开访问端口 8080、8081 和 8082,因此请确保您的错误与端口使用无关。
  • 您是否尝试按照我在回答中的建议进行操作?
  • 重要一点,您为什么要退回收藏?您应该在调用集合后执行某些操作,例如插入或删除......当您调用集合函数时,基本上 mongodb 返回一个准备在数据库中执行操作的结构。我建议你检查你的代码。如果您需要更多帮助,我在这里 ;)
  • @roman-sachenko 建议的代码永远不会工作,因为是 Mongoose 框架的代码,您使用的是 MongDB 原生框架。
  • @mujaffars 我更新了我的答案。看看那里。

标签: node.js mongodb cloud9-ide


【解决方案1】:

尝试返回这个:res.status(200).json({'myCollection' : collectionInfo});

您可以找到更多关于快速回复here的详细信息

更新:

在你解释完细节后,看看下面的代码:

app.post('/ajax-mongo-connect', function (req, res) {
    var mongoClient = new MongoClient(new Server('localhost', 27017));
    mongoClient.open(function(err, mongoClient) {
        if(err){
            console.log(err);
            res.status(500).json({message : 'OMG, an error occurred'});
        }else{
            var db = mongoClient.db("mydb");
            db.createCollection("students", { name : req.body.nm, description : req.body.desc, location : req.body.loc } );
            console.log('database connected',db);
            var collectionInfo = db.collection("students");
            // Here we will find all students
            collectionInfo.find({}).toArray(function(err, students) {
               // so now, we can return all students to the screen.
               res.status(200).json({'myCollection' : students});
            }
        }
    })
})

干杯!

【讨论】:

  • 基本上我需要返回存储在集合中的记录,以便在列表中显示它们。我也试过你的代码“res.status(200).json({'myCollection': collectionInfo});”但通过使用这个也页面挂起。我认为我们没有发回任何响应,因此等待响应的回调和页面变得无响应。不过让我知道我应该如何返回集合记录,以便我可以迭代它们并以表格列表格式显示。
【解决方案2】:

猫鼬 ODM

首先,我想推荐您使用 Mongoose ODM: https://github.com/Automattic/mongoose

这样您就可以更轻松地使用数据库。

基本上它会返回 (Mongoose) 普通对象作为结果,但如果出现问题,您可以尝试使用 toObject()toJSON() 或如上所述创建自己的对象,如 {data: mongoCollection}

例子:

res.send(collectionInfo.toObject());
res.send(collectionInfo.toJSON());
res.send({data: collectionInfo});

如有问题请参考链接:

http://mongoosejs.com/docs/guide.html#toJSON

原生驱动

对于原生驱动,它也应该返回正常构造的对象,但根据我过去遇到的问题,如果您手动设置标头,JSON.stringify 总是有帮助的。

您还可以检查您的实体的内容。所以你可以通过console.log(collectionInfo);输出它

然后确保里面有正确的对象。 根据结果​​,您可以采取以下措施:

  • res.send(JSON.stringify(collectionInfo)) //set headers manually
  • res.json(JSON.stringify(collectionInfo)) //you don't need to set headers

至少你会知道collectionInfo里面到底是什么。我认为调查这个问题就足够了。

【讨论】:

  • 我试过 res.send(collectionInfo.toJSON());和 res.send({data: collectionInfo});但它不工作并给出错误。我已经更新了问题并添加了有关错误的详细信息,请检查。
  • @roman-sachenko 请注意,他正在使用 MongoDB 本机驱动程序与数据库进行通信,您建议的代码适用于 Mongoose 框架,而不是本机驱动程序。请更正你的答案。
【解决方案3】:

您可以通过在 node.js 中执行此操作来查看循环 JSON 对象:

 const util = require('util') // Native node module

 util.inspect(circularObj)

您可以从代码中的任何位置调用它,因此用途非常广泛。

【讨论】:

    猜你喜欢
    • 2013-08-15
    • 1970-01-01
    • 2013-02-14
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 2020-08-02
    • 2012-10-18
    • 1970-01-01
    相关资源
    最近更新 更多