javascript - 如何将新对象添加到我包含在我的配置文件模型中的空数组中(mongodb/mongoose)
问题描述
这是我的个人资料模型,
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" }] });
}
}
);
大多数这些工作没有任何问题,我可以添加一个新帖子而没有任何错误,但是该帖子没有添加到我的个人资料中的帖子数组中。我想要的最终结果是记录用户的帖子,以便我可以在他的个人资料中单独显示它们。为什么这不起作用?请帮我!我是网络开发的新手,对此我感到很困惑。提前致谢。
解决方案
第一步是检查您的身份验证中间件是否收到令牌参数,第二步是检查该令牌是否有效。最后是检查你的“router.post”逻辑。
推荐阅读
- python - Python sys.stdout.flush() 似乎不起作用
- keras - 变分自动编码器:编码器是否必须具有与解码器相同的层数?
- java - AWS Lambda 中的资源释放
- c++ - 在 VS 2005 中获取编译器错误'二进制'<<':找不到运算符'
- jquery - 使用 JQUERY MODAL PHP 传递变量
- ubuntu-16.04 - 更新驱动程序 nvidia-396 后的 ubuntu 16.04 LTS 登录循环
- bash - unoconv 中的错误处理
- c++ - 使用像 typedef 这样的 decltype
- apache-spark - Spark Streaming 将查询参数传递给 Neo4j Scala
- angular - 如何绘制基于 svg 的 2D 平面图?