Skip to content

Instantly share code, notes, and snippets.

@codebubb
Created July 3, 2019 16:05
Show Gist options
  • Select an option

  • Save codebubb/8d6bfa75f4581f1f21033d18fea4d855 to your computer and use it in GitHub Desktop.

Select an option

Save codebubb/8d6bfa75f4581f1f21033d18fea4d855 to your computer and use it in GitHub Desktop.
MongoDB RestFul calls
router.get('/', (req, res, next) => {
const users = req.app.locals.users;
users
.find({})
.toArray()
.then(data => res.json(data));
});
router.post('/', (req,res, next) => {
const users = req.app.locals.users;
const document = req.body;
users
.insert(document)
.then(data => res.json(data));
});
router.get('/:id', (req, res, next) => {
const users = req.app.locals.users;
const id = ObjectId(req.params.id);
users
.findOne({ _id: id })
.then(data => res.json(data));
});
router.patch('/:id/languages', (req,res, next) => {
const users = req.app.locals.users;
const id = ObjectId(req.params.id);
const languages = req.body.languages;
users
.updateOne({ _id: id }, { $set: { languages: languages }})
.then(data => res.json(data));
});
router.put('/:id', (req,res, next) => {
const users = req.app.locals.users;
const id = ObjectId(req.params.id);
const document = req.body;
users
.replaceOne({ _id: id }, document)
.then(data => res.json(data));
});
router.delete('/:id', (req,res, next) => {
const users = req.app.locals.users;
const id = ObjectId(req.params.id);
users
.deleteOne({ _id: id })
.then(data => res.json(data));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment