首页 > 解决方案 > 将另一个集合中的文档保存在新文档的数组中

问题描述

我正在建立一个博客,我想在我的博文中动态列出产品。所以,我有一个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 }
);

标签: node.jsmongodbmongoose

解决方案


推荐阅读