MongoDB
When trying to write a user to the database I am getting errors in my console?

2

Asked 2 years ago,
Active 2 years ago,
1 comment
•  377 views
Codeinger123 asked this question 2 years ago
Codeinger123
2 years ago

When trying to write a new user to the mongo db i am getting an error when trying to save them to the database i have logged the incoming requests to the console and they all are working properly. If someone could take a look at my code and see what the problem is that would be awesome! Thanks in advance!


app.js

const express = require("express");
const cors = require ("cors");
const passport = require("passport");
const bodyParser = require("body-parser");
const  mongoose  = require("mongoose");
const User = require('./models/user');






var app = express();
app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(cors());
app.use(passport.initialize());
mongoose.connect(process.env.MONGO_URI, (err,res)=>{
    if(err){
        console.log("not connected to mongo")
    }else{
        console.log("connection successful")
    }
})


app.post("/user/signup", (res,res)=>{
    let newUser = new User({
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        email: req.body.email
    })
    newUser.save()
})






app.listen( 8080, () =>{
    console.log(`Server is listening on port: 8080`)
})


mongoose model:

const mongoose = require('mongoose');


new userSchema = new mongoose.Schema({
    firstName: string,
    lastName: string,
    email: string
})


module.exports = (userSchema)

console.log when starting server:

waltervannoy commented 2 years ago
Codeinger123 marked this answer 2 years ago
waltervannoy 2 years ago

Hello Codeinger123! I believe the reason for the error is because fist of all when you create a mongoose schema you should use syntax like this:

const mongoose = require('mongoose');


new userSchema = new mongoose.Schema({
    firstName: string,
    lastName: string,
    email: string
});


module.exports = mongoose.model('user',userSchema)

And also when when you save a mongo document it creates a promise which in the code snippet above you are not providing a callback for. Try something like this:

//add this import
const { json } = require("body-parser");

app.post("/user/signup", (res,res)=>{
    let newUser = new User({
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        email: req.body.email
    })
    newUser.save()
 .then(result => {
                res.json({
                  result: result
                });
              })
              .catch(err => {
                res.json({
                  error: err
                });
              });
});

Try this out and let me know if you are still getting an error or if it works.

4

1
relpy
answer
Leave a comment
Leave a comment