Ndroid21
Ndroid21

Reputation: 478

Getting error while saving documents using mongoose in node express.js project

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: {} }

Upvotes: 0

Views: 47

Answers (1)

Praveen AK
Praveen AK

Reputation: 611

                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

Upvotes: 1

Related Questions