Error while doing query

Asked

Viewed 128 times

0

I am building a Rest api with Node, but when trying to get a pass parameters returns all the data.

app js.

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const url = 'url de conexao';
const option = {reconnectTries: Number.MAX_VALUE, reconnectInterval: 500, poolSize: 5, useNewUrlParser: true};

mongoose.connect(url, option);
mongoose.set('useCreateIndex', true);

mongoose.connection.on('error', (err) => {
    console.log("Erro na conexao com o banco de dados! " + err);
});
mongoose.connection.on('disconnected', (err) => {
    console.log("Desconectado do banco de dados! " + err);
});
mongoose.connection.on('connected', () => {
    console.log('Conectado ao banco de dados!');
});

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

const vendaRoute = require('./routes/vendas');

app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});
app.use('/', vendaRoute);

app.listen(3000).on('listening', () => {
    console.log("Servidor rodando!");
});

module.exports = app;

sales.js (route)

const express = require('express');
const router = express.Router();
const Vendas = require('../models/venda');

router.get('/', (req, res) => {
    Vendas.find({}, (err, data) => {
        if(err) return res.send({error: "Erro ao realizar a consulta!"});
        return res.send(data);
    });
});
router.get('/:nome', (req, res) => {
    const nome = req.params.nome;
    Vendas.find({cliente: nome}, (err, data) => {
        if(err) return res.send({error: "Erro ao realizar a consulta!"});
        return res.send(data);
    });
});
router.post('/', (req, res) => {
    const {cliente, produto, valorProduto, lucro} = req.body;
    if (!cliente || !produto || !valorProduto || !lucro) return res.send({error: "Preencha todos os campos!"});
    Vendas.create(req.body, (err, data) => {
        if(err) return res.send({error: "Erro ao registrar! \n Tente novamente mais tarde!"});
        return res.send({message: "Registrado com sucesso!"});
    });
});

module.exports = router;

venda.js (model)

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const VendaSchema = new Schema({
    cliente: {type: String, required: true},
    produto: {type: String, required: true},
    valorProduto: {type: String, required: true},
    lucro: {type: String, require: true}
});

module.exports = mongoose.model('Venda', VendaSchema);
  • Please provide a little more detail. Is there an error? What is the error? Or... What is the expected output and what you are receiving?

  • Example: When going to localhost/ me returns all the data as it should, when going to localhost/? name=Luke it should return to me everyone who has the name Luke, however it continues returning all the data.

  • Your code creates a route to localhost/Lucas, the localhost/ route does not handle the url query

  • yes, that’s right, I had even answered right here, but someone erased

  • @Lucassimao, about having erased, in the Timeline of the question, it is possible to see that it was removed by voting, probably had some problem with the content of it

  • you need to load the schemas in the connection. to make the query.

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.