在节点express.js项目中使用猫鼬保存文档时出错

programmingArrow

即使在节点express.js项目中使用mongoose将文档保存到mongodb后,我也遇到错误。

这是我的代码:

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" });
    // }
}

我有两个问题:

  1. 我在userController中有注册方法。有什么办法可以在storeJob方法中使用该方法?
  2. 在上面的代码中,即使在将用户和作业保存到数据库并将它们链接起来之后,api响应也是
{ success: false, message: "Error while creating job.", error: {} }
Praveen AK
                user.jobs.push(createdJob);
                user.save();

在这种情况下,这两行将创建一个新用户,因为用户定义了用户架构。

代替这两行尝试

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

希望它对您有用。谢谢

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章