Recently, when using mongoose, I discovered a knowledge point that I had not paid attention to before. The following article mainly introduces you to the two methods of updating objects in mongoose, and compares the two methods in detail through sample code. To give everyone a better reference for learning, friends in need can refer to it.
Preface
Mongoose is an object model tool for convenient operation of mongodb in the node.js asynchronous environment
So To use it, you must first install node.js and mongodb. For an introduction to the installation and operation of mongodb, please refer to: //www.jb51.net/article/80296.htm
Demonstration
Description scenario
Update shopping cart quantity and check status
Business logic
Query the current user’s shopping cart object Cart, and update the quantity and selected fields passed by the front end
Method 1
var _ = require('underscore'); Cart.findOneAndUpdate({ _id: req.body.cart._id, user: user }, _.pick(req.body.cart, 'quantity', 'selected'), { new: true }, function(err, updatedCart) { res.send( utils.json({ data: updatedCart }) ); } );
Note: _.pick is equivalent to
{ quantity: req.body.cart.quantity, selected: req.body.cart.selected }
Method 2
var _ = require('underscore'); Cart.findOne({ _id: req.body.cart._id, user: user }, function(err, cart) { if (err) { console.log(err); } // 复制对象 _.extend(cart, req.body.cart); cart.save(function(err, updatedCart) { res.send( utils.json({ data: updatedCart }) ); }); } );
Comparison
The first code uses findOneAndUpdate in only one step, which is more concise and suitable for updates Scenarios with few and very clear fields
The second method is to findOne first and then save the entity. It uses underscore object copy, which makes the entire object operation more flexible and is suitable for scenarios with many and uncertain fields
Conclusion
Requirements are always changing, so I generally use the second option.
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to implement HTML attribute binding in Angular4
How to write the multiplication table using JS
Using JS to calculate the problem of buying 100 chickens
The above is the detailed content of There is a detailed introduction to updating objects in mongoose. For more information, please follow other related articles on the PHP Chinese website!