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

时间:2020-07-11 23:37:31

标签: javascript node.js mongodb express mongoose

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

这是我的代码:

<a href="#!" data-post-id="{{ post.id }}" class="btn btn-sm btn-{% if isLiked %}outline-primary post-unlike-link{% else %}white post-like-link{% endif %}">
                        <span class="fe fe-thumbs-up mr-2"></span>
                        <span id="post-like-count">{{ post.getLikedBy.count }}</span>
                    </a>

我有2个问题:

  1. 我在userController中有register方法。有什么办法可以在storeJob方法中使用该方法?
  2. 在上面的代码中,即使将用户和作业保存到数据库并将它们链接为api后,响应也是
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 个答案:

答案 0 :(得分:1)

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

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

代替这两行尝试一下

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

希望它对您有用。谢谢