Skip to content

Instantly share code, notes, and snippets.

@nguyenphuongduy124
nguyenphuongduy124 / gist:70a4c56f8b0411453cb2e340ea975267
Created May 26, 2020 17:42
MongoDB and Mongoose - Nối các truy vấn để thu hẹp kết quả tìm kiếm
If you don’t pass the callback as the last argument to Model.find() (or to the other search methods), the query is not executed. You can store the query in a variable for later use. This kind of object enables you to build up a query using chaining syntax. The actual db search is executed when you finally chain the method .exec(). You always need to pass your callback to this last method. There are many query helpers, here we’ll use the most ‘famous’ ones.
Find people who like burrito. Sort them by name, limit the results to two documents, and hide their age. Chain .find(), .sort(), .limit(), .select(), and then .exec(). Pass the done(err, data) callback to exec().
@nguyenphuongduy124
nguyenphuongduy124 / gist:cee9b365d9cc3e2d88ee25437c988721
Last active May 26, 2020 16:44
MongoDB and Mongoose - Thực hiện update bằng cách Find, Edit và Save
var findEditThenSave = function(personId, done) {
var foodToAdd = "hamburger";
Person.findById(personId, function(err, data){
if(err) return done(err);
data.favoriteFoods.push(foodToAdd);
data.save(function(errSave, data){
if(errSave) return done(errSave);
done(null, data)
});