gpt4 book ai didi

node.js - 如何在nodejs应用程序中输出mongodb集合以获取它们的响应

转载 作者:太空宇宙 更新时间:2023-11-04 00:52:34 26 4
gpt4 key购买 nike

我正在使用 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)

最佳答案

尝试返回: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});
}
}
})
})

干杯!

关于node.js - 如何在nodejs应用程序中输出mongodb集合以获取它们的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31701957/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com