Search code examples
javascriptmongodbmongoosepostmanmongoose-schema

How to save data in mongodb with express node.js?


I am encountering a problem when I try to make a post request with mogoose using the Postman, i get the following answer:

<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>

<body>
    <pre>Cannot POST /</pre>
</body>

</html> 

I can't understand the reason, my index.js code:

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

mongoose.connect(
  process.env.MONGODB_URL || "mongodb://localhost/trading",
  {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true,

  }
).then(item => {
  console.log('conectado com o banco')
}).catch((err)=>{
  console.log(err)
});

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

const candlesRoute = require("./routes/candles");
const home = require("./routes/home");

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", 'GET,PUT,POST,DELETE');

  app.use(cors());
  next();

})

app.use("/", home);
app.use("/candles", candlesRoute);

const PORT = 8080;
app.listen(PORT, () => {
  console.log("Servidor Conectado");
});

my route candles.js :

const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");

require("../models/Candles");
const candlesTick = mongoose.model("candles");

router.post('/candles', async (req, res) => {
  try {
    const velas = req.body

    await new candlesTick(velas).save();
      console.log('successe')
  } catch (error) {
    console.log(error);
  }
});

module.exports = router;

and finally my model Candles.js:

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

const Candles = new mongoose.Schema({
    titulo: {
        type: String, 
    },
    
})

mongoose.model("candles", Candles);

my request in the Postman is as follows

{
    "titulo": "DENT/ETH"
}

I have already tmbm send the data directly and even then it does not work, I do not understand the reason for this, please if anyone can help thanks


Solution

  • app.use("/candles", candlesRoute); will add namespace to that route and router also has candles in the post request. At the end the available route will be POST {{host}}/candles/candles.

    Please try remove candles from

    router.post('/candles', async (req, res) => {
      ...
    })
    

    or have the URL in postman as {{host}}/candles/candles