1

I have a MERN-stack app, in the server side, I create a new document to the DB and it works fine(I check it in Mongocompass). however, when fetching this data, I don't get the new saved document with the response even though it appears in the DB. For example, I have [1,2,3] in the db, I create a new document, 4. The actual DB is [1, 2, 3, 4], but when fetching it is [1, 2, 3].

The thing is, this issue happens ONLY in production, I host my server in a shared hosting service by Dreamhost. In local host everything works fine, and even in Heroku it worked fine.

Node.js version on my host: 12.18.3 Node.js version on my machine: 14.15.3 mongoose version: 5.12.7

here is my code: creating a new document:

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' });
});

fetching the products:

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

I've noticed that only after deleting a document from the DB it gets updated and fetches the latest collection, delete function is:

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'})
})

Problem Fixed : It turned out that the problem is not with mongoose, it actually is with browser caching. Fixed with the help of this question: No cache in Node.js server. Still, what I don't understand why there was not caching in neither when deployed in Heroku, nor in local host.

1 Answers1

0

Available options

new: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)

Solution Pass {new: true} if you want the updated result in the doc variable

Daniel
  • 935
  • 2
  • 6
  • 11
  • But what I need is the new doc shown when fetching all the docs because there are other instances where I fetch the docs in which the data will be lacking the new saved doc. – Tamerabdalrazaq Jul 27 '21 at 06:12