即使在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个问题:
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" });
// }
}
答案 0 :(得分:1)
user.jobs.push(createdJob);
user.save();
在这种情况下,这两行创建了一个新用户,因为用户定义了用户架构。
代替这两行尝试一下
var push = {
jobs:createdJob
}
var update = {
"$addToSet":push
}
await User.findOneAndUpdate({ "_id": savedUser._id },update).exec();
希望它对您有用。谢谢