Created
May 13, 2019 08:30
-
-
Save junibrosas/1831b031aaf9c8886cfa87d0b5873752 to your computer and use it in GitHub Desktop.
Mongoose CRUD sample codes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Find one and remove entity afterwards | |
Charity.findOne({ cuid: userCuid }); | |
.exec() | |
.then(entity => { | |
if (!entity) res.status(404).end(); | |
else { | |
entity.remove() | |
.then(() => res.status(204).end()); | |
} | |
}); | |
// Threading | |
Company.find(match).exec() | |
.then(companies => Promise.all(companies.map(addOpportunityToCompany(activity, contactEmail))) | |
.then(opportunities => ({...activity, opportunities}); | |
// Update a document | |
Charity.findOne({ cuid: req.params.cuid }) | |
.exec() | |
.then(entity => { | |
Object.assign(req.body.charity, entity).save() | |
.then(saved => res.status(200).json({ charity: saved }); | |
}); | |
// Get documents with sorting | |
Charity.find(match) | |
.sort('-dateAdded') | |
.exec() | |
.then(entities => res.json({ charities: entities }); | |
// Get single document | |
Charity.findOne({ cuid: req.params.cuid }) | |
.exec() | |
.then(entity => res.json({ charity: entity }); | |
// If Charity expired add it to feed | |
Charity.findOne({ cuid: req.params.cuid }) | |
.exec() | |
.then(activities => activities.forEach(activity => { | |
const isExpired = moment().isAfter(activity.endDate); | |
if(!isExpired) { | |
emitFeed({ | |
charityCuid: charity.cuid, | |
activityCuid: activity.cuid | |
}); | |
} | |
}); | |
// Sorting | |
Room.find({}).sort('-date').exec(function(err, docs) { ... }); | |
Room.find({}).sort({date: -1}).exec(function(err, docs) { ... }); | |
Room.find({}).sort({date: 'desc'}).exec(function(err, docs) { ... }); | |
Room.find({}).sort({date: 'descending'}).exec(function(err, docs) { ... }); | |
Room.find({}).sort([['date', -1]]).exec(function(err, docs) { ... }); | |
Room.find({}, null, {sort: '-date'}, function(err, docs) { ... }); | |
Room.find({}, null, {sort: {date: -1}}, function(err, docs) { ... }); | |
// Sorting with multiple sort fields | |
Article.find({}).sort({fieldA: 1, fieldB: 1}).exec(function(err, docs){...}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const emitFeed = (feed) => { | |
const { charityCuid, activityCuid } = feed; | |
return new Feed({ charityCuid, activityCuid }).save().catch(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment