简体   繁体   中英

Unable to fetch data in Json format from MongoDb using NodeJs

I am using Node.Js and MongoDb as a back-end service. I have 4 documents in my collection and each document has 3 fields named _id , Name and Image . All I want is to fetch data in Json format.

But it is showing error like:

错误图片

Here is my code:

var express = require('express');    
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true})); 

app.post('/offers',(req, res) => {

     MongoClient.connect(url, (err, db) => {           
        if(err) throw err;
        var obj = req.body.place;
        var dbo = db.db('Tiffino_db');

        dbo.collection("Offers")
            .find({ Name: obj },{ projection: { _id: 0 } })
            .toArray((err, result) => {
                 result.forEach((err, doc) => {
                     if (err) {
                         console.log("Error:", +err);
                     }
                     else { 
                        res.json({'Name':doc.Name},{'Image':doc.Image});
                    }
                });
            });
    });
});

Please let me know what I am doing wrong in above code.

Try this might help you

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {
   if (err) throw err;
   var dbo = db.db("mydb");
   dbo.collection("Offers").find({}).toArray(function(err, result) {
       if (err) throw err;
       console.log(result);
      db.close();
   });
});

Looking at this page http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#find , the main difference is your use of the forEach function which should look like this :

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true})); 

app.post('/offers',(req, res) => {

     MongoClient.connect(url, (err, db) => {           
        if(err) throw err;
        var obj = req.body.place;
        var dbo = db.db('Tiffino_db');

        dbo.collection("Offers")
            .find({ Name: obj },{ projection: { _id: 0 } })
            .toArray((err, result) => {
                 result.forEach((doc) => { // <-- removed err in forEach's fat arrow
                     if (err) {
                         console.log("Error:", +err);
                     }
                     else { 
                        res.json({'Name':doc.Name},{'Image':doc.Image});
                    }
                });
            });
    });
});

Not sure how it would produce NaN but forEach's callback first parameter certainly is the actual element in the array. This might hide error from toArray as well.

Let me know if that helps.

You need get rid from the "result.forEach" the result is already in array. res.json({'Name':doc.Name},{'Image':doc.Image}) => res.json(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM