如何使用Express和MongoDB将json从nodejs服务器发送到客户端js文件

时间:2022-06-25 09:53:06

I am new to Nodejs and Express and want to search some results from mongoDB and show it on client browser, i can find the values from the mongoDB query but not able to send it to client js file, It says doc is not defined, any help will be appreciated.

我是新来的NodeJS和Express和想要搜索MongoDB的一些成果,并显示在客户端浏览器,我可以找到从MongoDB的查询中值,但无法将其发送给客户端的js文件,它说的文档没有定义,任何帮助将不胜感激。

***app.js(Server)***
var bodyParser = require("body-parser");
var express = require("express");
var app = express();
var port = "8001";
var mongo= require('mongodb');
var mongoClient=mongo.MongoClient;
app.use(bodyParser.json());

app.use(express.static('public'));

app.get('/home', function(req, res) {
res.sendFile(__dirname + "/public/views/index.html");
});

app.listen(port, function() {
console.log("Server running at:" + port);
})

app.post("/response", function(req, res) {
var t = req.body;
mongoClient.connect("mongodb://localhost:27017/query", function(err,db){
cursor =db.collection('response').find({"name1":t.text},{"name2":1, "_id":0});
   cursor.each(function(err, doc) {
      if (doc != null) {
       console.log(doc);

      }

   });

})
res.send(doc);
});


***index.js(Client Side)***
$.ajax({
url: '/response',
type:"POST",
contentType:"application/json; charset=utf-8",
  complete: function(data) {
  console.log(data.responseText);
  alert(data.responseText);
}
});

2 个解决方案

#1


1  

doc is a variable local to your closure and therefore not available when you call res.send(doc).

doc是闭包的本地变量,因此在调用res.send(doc)时不可用。

In addition to that, you are iterating over all of your documents. You need to choose which one to return.

除此之外,您正在迭代所有文档。你需要选择返回哪一个。

I recommend something like this:

我推荐这样的东西:

cursor = db.collection('response').find({"name1":t.text},{"name2":1, "_id":0});
cursor.each(function(err, doc) {
   if (doc != null) {
       console.log(doc);
       return res.json(doc); // return the first document found
   }
});

Also note:

  • you should sanitize your data before passing it into the query
  • 您应该在将数据传递给查询之前清理数据

  • you shouldn't connect to the database on each request, instead set up mongo in the application context
  • 您不应该在每个请求上连接到数据库,而是在应用程序上下文中设置mongo

  • you should check err to see if mongo returned an error before trying to iterate the cursor
  • 你应该检查错误,看看mongo在尝试迭代游标之前是否返回了错误

EDIT:

To be more specific, the whole block should look like this:

更具体地说,整个块应该如下所示:

app.post("/response", function (req, res) {
    var t = req.body;
    mongoClient.connect("mongodb://localhost:27017/query", function (err, db) {
        if (err) {
            return res.json(err);
        }

        db.collection('tweets').findOne({"name1": t.text}, {"name2": 1, "_id": 0}, function (err, doc) {
            if (doc != null) {
                console.log(doc);
                return res.json(doc);
            }
            return res.sendStatus(404);
        });
    });
});

#2


0  

A few things:

  • cursor.each() has been deprecated in favour of cursor.forEach() assuming you're running a recent version of mongo
  • 假设您运行的是最新版本的mongo,已弃用cursor.each()以支持cursor.forEach()

  • Your first line in a callback should be something like if (err) { console.error(err) } - at this point you'd probably see that your query is invalid:
  • 回调中的第一行应该是if(err){console.error(err)} - 此时您可能会看到您的查询无效:

  • Your query should probably look like .find({'name1': t.text, 'name2': 1, '_id': 0})
  • 您的查询应该看起来像.find({'name1':t.text,'name2':1,'_ id':0})

  • If you are referencing an auto-generated mongo ObjectID as _id, you have to use '_id': new mongo.ObjectID(<whatever string holds the _id>) in order for it to work. If you didn't specify an _id on creation, the automatically generated ObjectID will require this.
  • 如果您将自动生成的mongo ObjectID作为_id引用,则必须使用'_id':new mongo.ObjectID( <任意字符串包含_id> )才能使其正常工作。如果在创建时未指定_id,则自动生成的ObjectID将需要此项。

  • The mongo docs are great, highly recommend leafing through them for examples and which bits take which arguments and the options for all of them.
  • mongo文档是伟大的,强烈建议翻阅它们的例子和哪些位获取所有参数和选项。

  • Consider using promises instead of callbacks to help tidy up. It's really easy with mongo - you just don't specify a callback function, and instead tack a .then(document => { ... }) on the end, and a single .catch(err => {console.error(err)}) will catch errors at the db, collection and cursor levels.
  • 考虑使用promises而不是回调来帮助整理。使用mongo非常简单 - 你只是不指定回调函数,而是在最后添加.then(document => {...})和单个.catch(err => {console.error(错误)})将捕获数据库,集合和游标级别的错误。

  • With jQuery, consider using .done(result => {...}) and .fail(err => { ... }) (aka promises) instead of complete for your ajax calls, and whatever you do, don't forget to attach an error handler. (I'm not even sure 'complete' is the right property, might depend on which jQuery you're using)
  • 使用jQuery,考虑使用.done(result => {...})和.fail(err => {...})(又名promises)而不是完成你的ajax调用,无论你做什么,都不要忘记附加错误处理程序。 (我甚至不确定'完整'是正确的属性,可能取决于你正在使用的jQuery)

  • If you're doing an AJAX POST you should probably attach some data (and a dataType)to it. Otherwise you'll still get no records because req.body will be undefined or empty.
  • 如果你正在进行AJAX POST,你应该附加一些数据(和一个dataType)。否则你仍然没有记录,因为req.body将是未定义或空的。

  • In the case of an error, you should be responding with res.status(500); res.end() at a minimum so you can tell when something has gone wrong on the server end.
  • 如果出现错误,您应该使用res.status(500)进行响应; res.end()至少可以告诉你服务器端出错的时间。

  • To help along, console.log(req.body) right at the top of your function so you know what data is arriving.
  • 为了帮助您,在您的函数顶部提供console.log(req.body),以便了解到达的数据。

  • Finally, if you intend on responding with JSON - use res.json(doc) instead of res.send(doc)
  • 最后,如果您打算使用JSON进行响应 - 请使用res.json(doc)而不是res.send(doc)

#1


1  

doc is a variable local to your closure and therefore not available when you call res.send(doc).

doc是闭包的本地变量,因此在调用res.send(doc)时不可用。

In addition to that, you are iterating over all of your documents. You need to choose which one to return.

除此之外,您正在迭代所有文档。你需要选择返回哪一个。

I recommend something like this:

我推荐这样的东西:

cursor = db.collection('response').find({"name1":t.text},{"name2":1, "_id":0});
cursor.each(function(err, doc) {
   if (doc != null) {
       console.log(doc);
       return res.json(doc); // return the first document found
   }
});

Also note:

  • you should sanitize your data before passing it into the query
  • 您应该在将数据传递给查询之前清理数据

  • you shouldn't connect to the database on each request, instead set up mongo in the application context
  • 您不应该在每个请求上连接到数据库,而是在应用程序上下文中设置mongo

  • you should check err to see if mongo returned an error before trying to iterate the cursor
  • 你应该检查错误,看看mongo在尝试迭代游标之前是否返回了错误

EDIT:

To be more specific, the whole block should look like this:

更具体地说,整个块应该如下所示:

app.post("/response", function (req, res) {
    var t = req.body;
    mongoClient.connect("mongodb://localhost:27017/query", function (err, db) {
        if (err) {
            return res.json(err);
        }

        db.collection('tweets').findOne({"name1": t.text}, {"name2": 1, "_id": 0}, function (err, doc) {
            if (doc != null) {
                console.log(doc);
                return res.json(doc);
            }
            return res.sendStatus(404);
        });
    });
});

#2


0  

A few things:

  • cursor.each() has been deprecated in favour of cursor.forEach() assuming you're running a recent version of mongo
  • 假设您运行的是最新版本的mongo,已弃用cursor.each()以支持cursor.forEach()

  • Your first line in a callback should be something like if (err) { console.error(err) } - at this point you'd probably see that your query is invalid:
  • 回调中的第一行应该是if(err){console.error(err)} - 此时您可能会看到您的查询无效:

  • Your query should probably look like .find({'name1': t.text, 'name2': 1, '_id': 0})
  • 您的查询应该看起来像.find({'name1':t.text,'name2':1,'_ id':0})

  • If you are referencing an auto-generated mongo ObjectID as _id, you have to use '_id': new mongo.ObjectID(<whatever string holds the _id>) in order for it to work. If you didn't specify an _id on creation, the automatically generated ObjectID will require this.
  • 如果您将自动生成的mongo ObjectID作为_id引用,则必须使用'_id':new mongo.ObjectID( <任意字符串包含_id> )才能使其正常工作。如果在创建时未指定_id,则自动生成的ObjectID将需要此项。

  • The mongo docs are great, highly recommend leafing through them for examples and which bits take which arguments and the options for all of them.
  • mongo文档是伟大的,强烈建议翻阅它们的例子和哪些位获取所有参数和选项。

  • Consider using promises instead of callbacks to help tidy up. It's really easy with mongo - you just don't specify a callback function, and instead tack a .then(document => { ... }) on the end, and a single .catch(err => {console.error(err)}) will catch errors at the db, collection and cursor levels.
  • 考虑使用promises而不是回调来帮助整理。使用mongo非常简单 - 你只是不指定回调函数,而是在最后添加.then(document => {...})和单个.catch(err => {console.error(错误)})将捕获数据库,集合和游标级别的错误。

  • With jQuery, consider using .done(result => {...}) and .fail(err => { ... }) (aka promises) instead of complete for your ajax calls, and whatever you do, don't forget to attach an error handler. (I'm not even sure 'complete' is the right property, might depend on which jQuery you're using)
  • 使用jQuery,考虑使用.done(result => {...})和.fail(err => {...})(又名promises)而不是完成你的ajax调用,无论你做什么,都不要忘记附加错误处理程序。 (我甚至不确定'完整'是正确的属性,可能取决于你正在使用的jQuery)

  • If you're doing an AJAX POST you should probably attach some data (and a dataType)to it. Otherwise you'll still get no records because req.body will be undefined or empty.
  • 如果你正在进行AJAX POST,你应该附加一些数据(和一个dataType)。否则你仍然没有记录,因为req.body将是未定义或空的。

  • In the case of an error, you should be responding with res.status(500); res.end() at a minimum so you can tell when something has gone wrong on the server end.
  • 如果出现错误,您应该使用res.status(500)进行响应; res.end()至少可以告诉你服务器端出错的时间。

  • To help along, console.log(req.body) right at the top of your function so you know what data is arriving.
  • 为了帮助您,在您的函数顶部提供console.log(req.body),以便了解到达的数据。

  • Finally, if you intend on responding with JSON - use res.json(doc) instead of res.send(doc)
  • 最后,如果您打算使用JSON进行响应 - 请使用res.json(doc)而不是res.send(doc)