简体   繁体   中英

Mongodb queries vs JavaScript Array method performance

To do simple update tasks or filtering tasks which should be used? For simple tasks as shown here, should I use Js Array methods, or mongodb queries?

I need an explanation.

try {
        let subCategory= await SubCategory.findById(req.params.subId);
        let previousSlug= subCategory.slug;
        
        let product= await Product.find({subCatSlug:previousSlug});

        product.forEach(el=>{
            
            el.subCatSlug=req.body.slug;
            el.subCatName=req.body.name;
            el.save();
            
        })
        
        subCategory= await SubCategory.findByIdAndUpdate(req.params.subId,req.body,{
            new: true,
            runValidators: true
        })
        
        res.json({
            data:subCategory,
            message:"Sub category is updated!"
        })
    }

or: here Id is passed from the body to update the data

try {
        const newData = req.body;

        const oldSubCategory = await SubCategory.findOne({_id: newData._id});

        await SubCategory.findByIdAndUpdate(req.body._id, req.body ,{
            new: true,
            runValidators: true
        })

        if(oldSubCategory.slug !== newData.slug || oldSubCategory.subCatName.trim() !== newData.subCatName.trim()){
            await Product.updateMany({subCatSlug:previousSlug}, {$set: {subCatSlug: req.body.slug, subCatName: req.body.subCatName}});
        }

        res.json({
            message: "Sub category is updated"
        })
    } catch (error) {
        if (!err.statusCode) {
            err.statusCode = 500;
            err.message = 'Something went wrong on database operation!'
        }
        next(err);
    }
}

updateMany() will always be faster than updating one document at a time with the save() method. Also I would suggest using the for of loop in case you are forced to update one document at a time because this loop allows use of await inside of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM