这是我的个人资料模型,
const ProfileSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
company: String,
website: String,
location: String,
status: {
type: String,
required: true,
},
skills: {
type: [String],
required: true,
},
bio: String,
githubusername: String,
experience: [
{
title: {
type: String,
required: true,
},
company: {
type: String,
required: true,
},
location: String,
from: {
type: Date,
required: true,
},
to: Date,
current: {
type: Boolean,
default: false,
},
description: String,
},
],
education: [
{
school: {
type: String,
required: true,
},
degree: {
type: String,
required: true,
},
fieldofstudy: {
type: String,
required: true,
},
from: {
type: Date,
required: true,
},
to: Date,
current: {
type: Boolean,
default: false,
},
description: String,
},
],
social: {
youtube: {
type: String,
},
twitter: {
type: String,
},
facebook: {
type: String,
},
linkedin: {
type: String,
},
instagram: {
type: String,
},
},
date: {
type: Date,
default: Date.now,
},
posts: [],
});
这就是我添加新帖子的方式,
router.post(
"/",
[auth, [check("text", "Text is required").not().isEmpty()]],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
try {
const user = await User.findById(req.user.id).select("-password");
let profile = await Profile.findOne({ user: req.user.id });
if (profile) {
const newPost = new Post({
text: req.body.text,
name: user.name,
avatar: user.avatar,
user: req.user.id,
});
const post = await newPost.save();
profile.posts.unshift(post);
res.json(post);
}
} catch (err) {
console.error(err.message);
res.status(500).json({ errors: [{ msg: "Server Error" }] });
}
}
);
大多数这些工作没有任何问题,我可以添加一个新帖子而不会出现任何错误,但是该帖子没有添加到我的个人资料中的帖子数组中。我想要的最终结果是保留用户帖子的记录,以便我可以在他的个人资料中单独显示它们。为什么这不起作用?请帮我!我是 Web 开发的新手,对此我感到很困惑。提前致谢。
我对您的问题的理解是您想将帖子添加到个人资料架构中。
const post = await newPost.save();
profile.posts.unshift(post);
await profile.save();
res.json(post);
你也需要调用 save ,你错过了。现在帖子将被推送到帖子字段中的个人资料集合。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句