1

models/users.js

const mongoose = require('mongoose');
const Joi = require('joi');


const User = mongoose.model('user', new mongoose.Schema({
    name  : {
        type : String,
        required:true,
        minlength : 5,
        maxlength : 50
    },
    email : {
        type:String,
        required:true,
        unique:true,
        minlength:5,
        maxlength:255
    },
    password : {
        type:String,
        required:true,
        minlength:8,
        maxlength:1024

    }

}));

function validateUser(user){
    const schema = {
        name : Joi.string().min(5).max(50).required(),
        email  : Joi.string().min(5).max(255).required().email(),
        password:Joi.string().min(5).max(255).required()
    };
    return Joi.validate(schema,user);
};

module.exports.User = User;
module.exports.validate=validateUser;

routes/users.js

const mongoose = require('mongoose');
const express = require('express');
const router = express.Router();
const bodyparser = require('body-parser');
const bodyEncodedParser = bodyparser.json();
const {User,validate}=require('../models/users');


router.post('/',bodyEncodedParser,async(req,resp)=>{
    const {error} = validate(req.body);
    if (error) return resp.status(400).send(error.details[0].message);
//to check if user already not registered

    let user = await User.findOne({email : req.body.email});
    if(user) return resp.status(400).send("user already registered");

    user = new User({
        name :req.body.name,
        email :req.body.email,
        password :req.body.password
    });

    await user.save();

    resp.send(user);

});

module.exports =router;

hi when i am running the from my app.js. programs runs fine and database is also connected. when i send POST request using postman with valid name email and password it gives me error. i want to achieve that when i send post rqst validation of my http body takes place which is in json format. if no email exists. the data i provided in http body gets added to the database. i dont understand why data dosent gets saved even i send a valid json object. everytime i send using post it give me following error. i have not done error handling yet when using await method.i know it will give me error then if i send a wrong json object. but why is it giving me error when sending correct json object via POST using postman

nhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON
    at JSON.stringify (<anonymous>)
    at stringify (C:\Users\AMIT SINGH\Desktop\vidly\node_modules\express\lib\response.js:1119:12)
    at ServerResponse.json (C:\Users\AMIT SINGH\Desktop\vidly\node_modules\express\lib\response.js:260:14)
    at ServerResponse.send (C:\Users\AMIT SINGH\Desktop\vidly\node_modules\express\lib\response.js:158:21)
    at router.post (C:\Users\AMIT SINGH\Desktop\vidly\routes\users.js:12:40)
    at Layer.handle [as handle_request] (C:\Users\AMIT SINGH\Desktop\vidly\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\AMIT SINGH\Desktop\vidly\node_modules\express\lib\router\route.js:137:13)
    at jsonParser (C:\Users\AMIT SINGH\Desktop\vidly\node_modules\body-parser\lib\types\json.js:101:7)
    at Layer.handle [as handle_request] (C:\Users\AMIT SINGH\Desktop\vidly\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\AMIT SINGH\Desktop\vidly\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\AMIT SINGH\Desktop\vidly\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\AMIT SINGH\Desktop\vidly\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\AMIT SINGH\Desktop\vidly\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\AMIT SINGH\Desktop\vidly\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\AMIT SINGH\Desktop\vidly\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (C:\Users\AMIT SINGH\Desktop\vidly\node_modules\express\lib\router\index.js:174:3)(node:5452) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:5452) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
amit
  • 11
  • 1
  • 2
  • 1
    Possible duplicate of [JSON.stringify, avoid TypeError: Converting circular structure to JSON](https://stackoverflow.com/questions/11616630/json-stringify-avoid-typeerror-converting-circular-structure-to-json) – David784 Jul 15 '18 at 13:54
  • and here is another algorithm (which I prefer acutally) for dealing with circular references: https://gist.github.com/zmmbreeze/9408172 – David784 Jul 15 '18 at 13:57
  • hey why shall i use Json.stringify . i want my json object which am sending via http body req to get stored in my schema. i have used same code to store values in my other modules. it worked. can u pls help me figure out whats wrong here – amit Jul 15 '18 at 14:36
  • Even if you're not using JSON.stringify, mongoose apparently is. Look at the first reference in your call stack: `JSON.stringify`. If you try to stringify an object with a self-reference (aka circular reference), this is the error you get. – David784 Jul 15 '18 at 14:42
  • well i reversed the parameters in joi.validate() and it worked. – amit Jul 15 '18 at 14:45
  • Just incase if it helps anybody... I forgot to use async and await when this error happened to me. – abrsh Jan 21 '21 at 13:47

0 Answers0