node.js - 将另一个集合中的文档保存在新文档的数组中
问题描述
我正在建立一个博客,我想在我的博文中动态列出产品。所以,我有一个array
叫做“内容”的东西。在这个数组中是:“content”和“asin-id”(它是一种产品 ID)。
但是,我需要整个产品文档来动态地将产品包含在我的博文中,而不是 asin-id。当我更新/编辑原始产品文档时,博客文章中的产品会自动更新,这一点也很重要。
我尝试遍历“内容” array
,获取 asin-id 并尝试获取特定的产品文档并将其推送到数组中。不幸的是,它不能以这种方式工作。
可视化:内容数组
content: [{ content: "some text", asin: "asinID" }, ...]
我试过的
exports.createBlogPost = async (req, res) => {
const content = req.body.content
content.forEach(element => {
const asin = element.asin
const product = Product.findOne({ asin: asin })
element.product = product
})
try {
const post = new BlogPost({
postTitle: req.body.postTitle,
content: content,
mainImage: req.file
})
await post.save()
if(post) {
return res.status(200).json({
success: true,
message: 'Saved blog post successfully',
post: post
})
}
} catch(err) {
console.log(err)
}
}
博文架构
const BlogPostSchema = new Schema(
{
postTitle: String,
mainImage: Array,
content: Array,
},
{ timestamps: true }
);
解决方案
推荐阅读
- r - 只提取 _ 之后的字母,中间有数字
- c++ - 隐藏超出边界的 QGraphicsItem 区域
- php - 如何在本地 Web 系统上执行自我更新?
- responsive-design - Bootstrap4 响应式导航栏在调整大小时包装文本
- android - SQLite 无法读取表中的字段
- matlab - 如何检查二维 Matlab 数组中是否存在一对值?
- javascript - 循环遍历二维数组并将数据提取到新数组
- jquery - 使用 jQuery 根据菜单下拉选择更新价格
- python - Python-Pam 错误输出 - SyntaxError: invalid syntax
- java - 如何在 Spring Boot 中更改 OAuth2 的过滤级别?