简体   繁体   中英

RangeError: Maximum call stack size exceeded (MongoDB-mongoose)

Trying to save user details into MongoDB Atlas and I use Postman for API interface. req.body contains the JSON request sent (POST) using postman. The JSON fails to get passed to the backend and Postman throws the following error:

RangeError-Maximum call stack size exceeded

错误信息.

controllers/user.js

const User = require('../models/user')

exports.signup = (req,res)=>{
    console.log("req.body",req.body);
    const user = new User(req.body);
    user.save((err,user)=>{
        if(err){
            return res.status(400).json({
                err
            });
        }
        res.json({
            user
        });
    });


};

routes/user.js

const express=require('express')
const router=express.Router()


const { signup } = require("../controllers/user");

router.post("/signup",signup) 


module.exports = router;

app.js


const express=require('express')
const mongoose=require('mongoose')
require('dotenv').config() //use env variables


const morgan = require('morgan')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')



//import routes
const userRoutes=require('./routes/user');
//app
const app=express()

//db

mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGO_URI,{
    useNewUrlParser:true,
    useCreateIndex: true,
    useUnifiedTopology: true
}).then(()=>{
    console.log('DB Connected');
}).catch(err=>console.log(err));

mongoose.connection.on('error',err=>{
    console.log(`DB connection error :${err}`)
})

//routes

app.use(morgan('dev'))
app.use(bodyParser.json())
app.use(cookieParser())

//routes middleware
app.use("/api",userRoutes);
const port=process.env.PORT || 8000;




app.listen(port,()=>{
    console.log(`Server is running on ${port}`);
});

vs-code 终端出错

If your user object has circular references, the res.json can fail. You can stringify the response before sending it over amd chose properties. something like

res.send(JSON.stringify(user, ['firstname', 'lastname', 'age']))

In your Project Go to Models Folder and then in user.js put this :

userSchema.virtual("password")
  .set(function(password){
    this._password=password;
    this.salt=uuidv4()
    this.encry_password=this.securePassword(password)
  })
  .get(function(){
    return this._password;
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM