【问题标题】:Mongoose creates a new document in the db, but does not fetch the updated collection in productionMongoose 在数据库中创建一个新文档,但不会在生产中获取更新的集合
【发布时间】:2021-10-01 07:52:00
【问题描述】:

我有一个 MERN 堆栈应用程序,在服务器端,我为数据库创建了一个新文档,它工作正常(我在 Mongocompass 中检查它)。但是,在获取此数据时,即使新保存的文档出现在数据库中,我也没有得到带有响应的新保存文档。例如,我在 db 中有 [1,2,3],我创建了一个新文档,4。实际的 DB 是 [1,2,3,4],但是在获取时它是 [1,2,3] .

问题是,这个问题只发生在生产中,我将我的服务器托管在 Dreamhost 的共享托管服务中。在本地主机中一切正常,甚至在 Heroku 中也能正常工作。

我主机上的 Node.js 版本:12.18.3 我机器上的 Node.js 版本:14.15.3 猫鼬版本:5.12.7

这是我的代码: 创建一个新文档:

router.post('/upload', async(req, res) => {
    const path = `${__dirname}/../static`
    const file = req.files.file;

    const newProduct = new Product({
        ...req.body,
        imageSrc: `${file.name}`,
        cardDetails: req.body.description,
    })
    
    let error = false
    file.mv(`${path}/${file.name}`, err => {
      if (err) {
        console.log('error downloading');
        console.error(err);
        error = err
      }
    });
    if(error) {
        return res.status(500).send(error)
    };

    try{
        await newProduct.save()
        await Category.findOneAndUpdate({title: req.body.category}, {
            $addToSet: {products: newProduct._id} 
        })
    } catch(err){
        if (err) return res.json({message: err})
    }

    res.json({ fileName: file.name, filePath: `/uploads/${file.name}`, message: 'Done' });
});

获取产品:

router.get('/', async(req, res) => {
    const response = await Product.find({})
    res.send(response)
})

我注意到只有在从数据库中删除一个文档后,它才会更新并获取最新的集合,删除函数是:

router.delete('/', async(req, res) => {
    const { _id, category } = req.body
    const prod = await Product.findById(_id)
    await Product.findByIdAndDelete(_id)
    await Category.findOneAndUpdate(
        {title: category}, {$pull: { products: mongoose.Types.ObjectId(_id)}}
    )
    res.send({status: 'ok'})
})

问题已解决:原来问题不在于 mongoose,而实际上是浏览器缓存问题。在这个问题的帮助下修复: No cache in Node.js server。 不过,我不明白为什么部署在 Heroku 和本地主机中时都没有缓存。

【问题讨论】:

    标签: node.js reactjs mongodb mongoose mern


    【解决方案1】:

    可用选项

    new: bool - 如果为真,则返回修改后的文档而不是原始文档。默认为 false(在 4.0 中更改)

    解决方案 如果您希望 doc 变量中的更新结果,请传递 {new: true}

    【讨论】:

    • 但是我需要的是在获取所有文档时显示的新文档,因为在其他情况下我获取的文档中的数据将缺少新保存的文档。
    猜你喜欢
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    • 2021-03-10
    • 2021-02-24
    • 2012-10-07
    相关资源
    最近更新 更多