0

I am getting error even after saving document to the mongodb using mongoose in node express.js project.

Here's my code:

exports.storeJob = async (req, res, next) => {
    const { name, email, password, title, location, descriptionUrl, tags, company, companyLogo, coupon, showLogo, highlightWithColor, customColor, makeSticky } = req.body;

    const { error } = userRegisterValidation(req.body);
    if (error) return res.status(400).json({ success: false, message: error.details[0].message });

    const emailExists = await User.findOne({ email: email });
    if (emailExists) return res.status(400).json({ success: false, message: "User already exits. Please Login" });

    const salt = await bcrypt.genSalt(10);
    const hashPassword = await bcrypt.hash(password, salt);

    const user = new User({
        name: name,
        email: email,
        password: hashPassword
    });
    
    // try{
        const savedUser = await user.save();

        const job = new Job({
            title,
            location,
            descriptionUrl,
            tags,
            company,
            companyLogo,
            coupon,
            showLogo,
            highlightWithColor,
            customColor,
            makeSticky,
            status: 'open',
            user: savedUser
        });
        try {
            const createdJob = await job.save();
            // try {
                user.jobs.push(createdJob);
                user.save();

            res.status(201).json({ success: true, data: savedUser });                
            // } catch {
            //     res.status(400).json({ success: false, message: "Some error occured" });
            // }
        } catch (err) {
            res.status(400).json({ success: false, message: "Error while creating job.", error: err });
        }
    // } catch(err) {
    //    res.status(400).json({ success: false, message: "Error while creating user" });
    // }
}

I have 2 questions:

  1. I have register method in userController. Is there any way to use that method inside storeJob method?
  2. In the above code even after saving user and job to the database and linking them api response is
{ success: false, message: "Error while creating job.", error: {} }

1 Answer 1

1
                user.jobs.push(createdJob);
                user.save();

In that case, this two lines creates a new user, because user defines the User schema.

Instead of these two lines try this

    var push = {
        jobs:createdJob
    }
    var update = {
        "$addToSet":push
    }
    await User.findOneAndUpdate({ "_id": savedUser._id },update).exec();

Hope it will work fine to you. Thanks

Sign up to request clarification or add additional context in comments.

2 Comments

const savedUser = await user.save(); ==> this line You already did in above
Use this then await User.findOneAndUpdate({ "_id": savedUser._id },update,{ new: true}).exec(async (err, savedUser) => {})

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.