MongoDB with node.js trying to make a new file (JavaScript)

Viewed 47

I wrote a little of code to start learning MongoDB with Node.js in JavaScript but it doesn't work but it doesn't give a error while running probably someone can help me with that.

The Main code:

const mongoose = require('mongoose');
const express = require('express');
const test = express();
const Blog = require('./bdSchema');


//connec to mongodb
const dbURI = 'mongodb+srv://Carsten:<int the real code the password is here>@cluster0.w6iwv.mongodb.net/tomhatesgeschaft?retryWrites=true&w=majority';
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
    .then((result) => console.log("connected to db"))
    .catch((err) => console.log(err))



test.get('/add-tomhatesgeschaft', (req, res) => {
    const tomhatesgeschaft = new Blog({
        title: 'hi'
    });
    tomhatesgeschaft.save()
        .then((result) => {
            res.send(result)
        })
        .catch((err) => {
            console.log(err);
        });
})

The BDSchema:

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

const BDSchema = new Schema({
    title: {
        type: String,
        required: true,
    },
});

const Blog = mongoose.model('Blog', BDSchema);
module.exports = Blog;
1 Answers

In your Node.js code, change the save function as below.

    tomhatesgeschaft.save((err,result) => {
    if (err){
        console.error(err);
    }
    else{
        res.send(result)
    })
})

OR

test.get('/add-tomhatesgeschaft', async (req, res) => {
    const tomhatesgeschaft = new Blog({
        title: 'hi'
    });
    try {
      await tomhatesgeschaft.save()
    } catch(error) {
      console.error(error)
    }
})

PS: You should not use GET requests for operations such as saving data to the database. Ideally, you should use a POST request.

Example with async:

test.post('/add-tomhatesgeschaft', async (req, res) => {
    const tomhatesgeschaft = new Blog({
        title: 'hi'
    });
    try {
      await tomhatesgeschaft.save()
    } catch(error) {
      console.error(error)
    }
})
Related