NodeJs is returning first document only

mongodb findone nodejs
mongodb findone by _id
node js mongodb find by _id
node js mongodb find by name
node js mongodb find limit sort
mongodb nodejs
node.js mongodb find toarray
mongoose find

I am using NodeJs and MongoDb as a back-end service.In my collection i have several documents having fields named _id and Name but Node is returning only first document and showing error in console.I want to fetch only Name field of a document.

Error:

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 dbo = db.db('Tiffino_db');

    dbo.collection("Offers")
        .find({},{ projection: { _id: 0 } })
        .toArray((err, result) => {
             if (err) {
                     console.log("Error:", +err);
                 }
                 else { 
                    for(var i = 0;i<result.length;i++){
                      res.send(result[i].Name);
                    }
                   db.close();
                }
           });
     });
});

Please let me know what I did wrong in above code.

THANKS


It looks like you're trying to send multiple responses in a loop using Response.Send() as a response is only sent once. This won't work, you'll need to create an array of names, and then use Response.Send() to do this once.

Using res.send(result.map(r => r.name)) would probably work

Mongoose return only one element from document's nested array , Mongoose return only one element from document's nested array · node.js mongodb mongoose. I'd like to fetch a single element within an array in my document,  The API reference documentation provides detailed information about a function or object in Node.js. This documentation indicates what arguments a method accepts, the return value of that method, and what errors may be related to that method. It also indicates which methods are available for different versions of Node.js.


You should aggregate the results into a variable and then call res.send() only once:

let resultString;
for(var i = 0;i<result.length;i++){
   resultString += result[i].Name + '\n';
}
res.send(resultString);

If you want to stream the results, you can use res.write() and when done call res.end()

Node.js MongoDB Find, method is a query object. In this example we use an empty query object, which selects all documents in a collection (but returns only the first document). Return the Specified Fields and the _id Field Only¶ A projection can explicitly include several fields by setting the <field> to 1 in the projection document. The following operation returns all documents that match the query. In the result set, only the item, status and, by default, the _id fields return in the matching documents.


You can not use res.send() multiple time in a for loop, try somthing like this

var data=[];
for(var i = 0;i<result.length;i++){
                  data.push(result[i].Name);
                }
res.send(data);

Node.js MongoDB Limit, Node.js MongoDB Limit Example. Limit the result to only return 5 documents: As you can see from the result above, only the 5 first documents were returned. Returns: One document that satisfies the criteria specified as the first argument to this method. If you specify a projection parameter, findOne() returns a document that only contains the projection fields. The _id field is always included unless you explicitly exclude it.


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

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

    dbo.collection("Offers")
        .find({},{ projection: { _id: 0 } })
        .toArray((err, results) => {
             if (err) {
                     console.log("Error:", +err);
                 }
                 else { 

                   response = results.map(result => result.Name);
                   //res.send(response);
                   // in json format
                   res.json(response);
                   db.close();
                }
           });
     });
});

db.collection.findOne(), One document that satisfies the criteria specified as the first argument to this method. If you specify a projection parameter, findOne() returns a document that only  To select data from a collection in MongoDB, we can use the findOne () method. The findOne () method returns the first occurrence in the selection. The first parameter of the findOne () method is a query object. In this example we use an empty query object, which selects all documents in a collection (but returns only the first document).


...
...
else { 
    output = result.map(offer => offer.name);
    res.send({output});
    db.close();
}

This should work as you can only send response once on a single response object and you are calling that for results.length times.

Queries, findOne is a convinence method finding and returning the first match of a query while regular find returns a cursor object instead. Use it when you expect only  The find () method returns the value of the first element in the provided array that satisfies the provided testing function. var array1 = [5, 12, 8, 130, 44]; var found = array1.find (function (element) { return element > 10; }); console.log (found); // expected output: 12. The source for this interactive example is stored in a GitHub


Advanced Node.js Development: Master Node.js by building , Master Node.js by building real-world applications Andrew Mead kind of like findOne: it's going to match that very first document, only it's going to remove it. This will also return the document so you can do something with the removed data. Executing db.collection.find () in the mongo shell automatically iterates the cursor to display up to the first 20 documents. Type it to continue iteration. To access the returned documents with a driver, use the appropriate cursor handling mechanism for the driver language. Read Concern ¶ To specify the read concern for db.collection.find


Collection(), The first findAndModify command modifies a document and returns the modified oplogReplay {Boolean, default:false} sets an internal flag, only applicable for  The first parameter of the updateOne() method is a query object defining which document to update. Note: If the query finds more than one record, only the first occurrence is updated. The second parameter is an object defining the new values of the document.


Practical Node.js: Building Real-World Scalable Web Apps, Model.find(query, [fields], [options], [callback(error, docs)]): Finds documents that first document that matches the query (if present) and updates it, returning the [callback(error, doc)]): Similar to findOneAndUpdate using only the ID • Model. The res object represents the HTTP response that an Express app sends when it gets an HTTP request. Following is the list of few properties associated with response object. This property holds a reference to the instance of the express application that is using the middleware. Boolean property that indicates if the app sent HTTP headers for the