Problems showing queries result in express + mongodb

1

Hi, I am trying to make an API that, given some ids, returns an array with each object found. The problem is that the app breaks when I consult the api as shown below. I would like someone to help me with what is happening as I am new with node.js and I do not see where my error is. Thanks

http://localhost:3000/calculatePrice?id[0]=1234&qty[0]=2&id[1]=123456&qty[1]=3

---------- Console -------------

   nodemon] restarting due to changes...
   [nodemon] starting 'node index.js'
   Listening on port 3000
   { _id: 5acbd85c6116cc38b42b223a,
   id: '1234',
   name: 'perro',
   price: 40,
   __v: 0 }
  1234
  { _id: 5acbda3fac2c811e6cce87fc,
  id: '123456',
  name: 'gato',
  price: 10,
  __v: 0 }
 123456
 events.js:183
  throw er; // Unhandled 'error' event
  ^

Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ServerResponse.setHeader (_http_outgoing.js:498:3)
at ServerResponse.header 


 D:\Programacion\proyects\petStore\node_modules\express\lib\
 response.js:767:10)
 at ServerResponse.send 
(D:\Programacion\proyects\petStore\node_modules\express\lib\
response.js:170:12)
at ServerResponse.json 
 (D:\Programacion\proyects\petStore\node_modules\express\lib\
response.js:267:15)
at Toy.findOne (D:\Programacion\proyects\petStore\index.js:119:10)
at 
D:\Programacion\proyects\petStore\node_modules\mongoose\lib\
model.js:3950:16
at process.nextTick 
(D:\Programacion\proyects\petStore\node_modules\mongoose\lib\
 query.js:2016:28)
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
[nodemon] app crashed - waiting for file changes before starting...

---------------- API Code (Schema Mongo)

var mongoose = require('mongoose');


mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var toySchema = new Schema( {
id: {type: String, required: true, unique: true},
name: {type: String, required: true},
price: Number
} );


module.exports = mongoose.model('Toy', toySchema);

------- API code index.js ---------

var express = require('express');
var app = express();

//Aqui configuramos el middleware
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
//Incluimos los modelos
var Toy = require('./Toy.js');

app.use('/calculatePrice', (req, res) => {
const { id, qty } = req.query;
var toy = {};
var toys = [];  
var subtotal = 0;
    toy.identificadores = id;
    toy.cantidades = qty;
    if(Object.keys(toy).length != 0){
        toy.identificadores.map((ident)=>{
        var query = {};
        query.id = ident;
        Toy.findOne(query, (err, juguete)=>{
            if(err){
              res.json(err);
            }else{  
                console.log(juguete);
                console.log(query.id);
                toys.push(juguete);
                res.json(toys);
            }
        });
    });
}else{
    res.json({});
}
});
//Configuracion del servidor
app.listen(3000, () => {
console.log('Listening on port 3000');
}); 
    
asked by user3821102 04.05.2018 в 17:42
source

1 answer

0

I do not know if it's because of the difference of findOne and find

  • findOne (): returns the first document
  • find (): returns all documents with which it matches

I hope that can help you

MongoDb Official

    
answered by 11.05.2018 в 21:24