1

The function in the model file works successfully. But to know if there is any duplication in the ID during registering and validate it, I made a return statement in the function. and according to the value of x that is assigned to the function (in the controller file) the server will respond.

//Model file
const bodyParser = require('body-parser');
const express = require('express');
const { check, validationResult } = require('express-validator');
const router = require('express').Router();
router.use(express.json());
const urlencoded = bodyParser.urlencoded({ extended: false });
const User = require('../DB/User.js'); //

function create_user(id1, name1, Password1) {
    var user1 = new User({
        id: id1,
        name: name1,
        Password: Password1
    });
    let x;
    user1.save(function(err) {
        if (err) {
            if (err.code == 11000) {
                x = 0;
                console.log('user already exists and x= ' + x);
                return x;
            } else {
                console.log(err);
            }
        } else {
            x = 1;
            console.log('Saved successfully and x =' + x);
            return x;
        }
    })
}
module.exports = create_user;

//Controller file
const bodyParser = require('body-parser');
const express = require('express');
const { check, validationResult } = require('express-validator');
const { x } = require('joi');
const create_user = require('../model/Registration.js');
const router = require('express').Router();
router.use(express.json());
const urlencoded = bodyParser.urlencoded({ extended: false });



router.get('/Registration', function(req, res, next) {
    res.render('Registration', { checker: 0 });
});

router.post('/Registraion/sign_up', function(req, res) {
    let x = create_user(req.body.id, req.body.name, req.body.password);
    console.log('x =' + x);
    if (x == 0) {
        req.body.id.setCustomValidity("This id is already used");
        console.log('this id exsists and x =' + x); //the output here is x= undefined
    } else {
        res.redirect('/Registration');
    }
});

module.exports = router;

0

1 Answer 1

1

Because user1.save is async and create_user doesn't wait for it to be resolved before returning, so it returns null.

you can solve that using a callback or an async await pattern

try this:

function create_user(id1, name1, Password1, callback) {
    var user1 = new User({
        id: id1,
        name: name1,
        Password: Password1
    });
    let x;
    user1.save(function(err) {
        if (err) {
            if (err.code == 11000) {
                x = 0;
                console.log('user already exists and x= ' + x);
                callback(x);
                return x;
            } else {
                console.log(err);
            }
        } else {
            x = 1;
            callback(x);
            console.log('Saved successfully and x =' + x);
            return x;
        }
    })
}


//Controller file
router.post('/Registraion/sign_up', function(req, res) {
    create_user(req.body.id, req.body.name, req.body.password, function(x) {
      console.log('x =' + x);
      if (x == 0) {
        req.body.id.setCustomValidity("This id is already used");
                console.log('this id exsists and x =' + x); //the output here is x= undefined
            } else {
                res.redirect('/Registration');
            }
        });
});
Sign up to request clarification or add additional context in comments.

1 Comment

First of all thanks for help, but I've tried it did not work. The function works very well if the ID was unique and the data become saved in the database, and if the ID was duplicated the function doesn't save and that's good. But in both cases, the function returns undefined whether if the ID was duplicated or not, and as i mentioned the function save the data successfully.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.