Just started learning how to use MongoDB and i keep experiencing this error : JSON.stringify

Viewed 27

I am new to programming and I have this error while doing a project. I would really appreciate your help

ERROR:

: JSON.stringify(value);
^

TypeError: Converting circular structure to JSON --> starting at object with constructor 'Socket'
| property '_writableState' -> object with constructor 'WritableState'
| property 'afterWriteTickInfo' -> object with constructor
'Object'
--- property 'stream' closes the circle
at JSON.stringify () ^

[nodemon] app crashed - waiting for file changes before starting...

version node: v16.16.0
version mongo: 4.0

my user creator:

import express from 'express';
import User from '../models/user';

const app = express();

app.post('/create', async (req, res)=>{
  const data = await User.create(req.body).catch(e => res.status(400).json({ok: false, e}));
  res.status(201).json({ok: true, data});
});

module.exports = app;

my user model:

import mongoose from 'mongoose';
import uniqueValidator from 'mongoose-unique-validator';
import privatePaths from 'mongoose-private-paths';

const UserSchema = new mongoose.Schema({
  name:{
    type: String,
    required: true
  },
  phone:{
    type: Number,
    required: true,
    unique: true
  },
  email:{
    type: String,
    required: true,
    unique: true
  },
  address:{
    type: String,
    required: false
  },
  city:{
    type: String,
    required: true,  
  },
  password:{
    type: String,
    required: true,
    private: true
  },
  role:{
    type: String,
    enum: ['admin','employee','user'],
    defautl: 'user'
  }
});

UserSchema.statics.create = function createUser(data){
  return new this(data).save();
}

UserSchema.plugin(privatePaths);
UserSchema.plugin(uniqueValidator,{message: '{PATH} should be unique'});

module.exports = mongoose.model('User', UserSchema);

My app:

import express from 'express';
import mongoose from 'mongoose';
import bodyparser from 'body-parser';
import controllers from './bin/controllers/user'

require('./config/config');

const app = express();

app.use(controllers);

app.use(bodyparser.json());

mongoose.connect(process.env.URL_DATABASE, {
    useUnifiedTopology: true,
    useNewUrlParser: true,

})
    .then(db => console.log('Connect to DB'))
    .catch(err => console.log(err));

module.exports = app;

{
    "ok": false,
    "e": {
        "errors": {
            "password": {
                "name": "ValidatorError",
                "message": "Path `password` is required.",
                "properties": {
                    "message": "Path `password` is required.",
                    "type": "required",
                    "path": "password"
                },
                "kind": "required",
                "path": "password"
            },
            "city": {
                "name": "ValidatorError",
                "message": "Path `city` is required.",
                "properties": {
                    "message": "Path `city` is required.",
                    "type": "required",
                    "path": "city"
                },
                "kind": "required",
                "path": "city"
            },
            "email": {
                "name": "ValidatorError",
                "message": "Path `email` is required.",
                "properties": {
                    "message": "Path `email` is required.",
                    "type": "required",
                    "path": "email"
                },
                "kind": "required",
                "path": "email"
            },
            "phone": {
                "name": "ValidatorError",
                "message": "Path `phone` is required.",
                "properties": {
                    "message": "Path `phone` is required.",
                    "type": "required",
                    "path": "phone"
                },
                "kind": "required",
                "path": "phone"
            },
            "name": {
                "name": "ValidatorError",
                "message": "Path `name` is required.",
                "properties": {
                    "message": "Path `name` is required.",
                    "type": "required",
                    "path": "name"
                },
                "kind": "required",
                "path": "name"
            }
        },
        "_message": "User validation failed",
        "name": "ValidationError",
        "message": "User validation failed: password: Path `password` is required., city: Path `city` is required., email: Path `email` is required., phone: Path `phone` is required., name: Path `name` is required."
    }
}

1 Answers

The syntax you are using is wrong. async/await helps you write synchronous-looking JavaScript code that works asynchronously, so you need to use try/catch syntax.

try {
    // Some validation
    const { password } = req.body
    if (!password) {
        const error = new Error("Missing password")
        error.code = 400
        throw error
    }
    const user = await User.create(req.body)
    res.status(200).json({ user })
} catch (error) {
    throw new Error(error.message)
}

To use the chain "catch" like you are using it would be:

User.create(req.body).then((user) => { res.status(200).json({ user }) }).catch(error => { throw new Error(error.message) } )
Related