@mongodb-model/model
v0.0.1
Published
Mongodb Model
Downloads
18
Readme
Mongodb Model
Model is an exceptional and dynamic tool that excels in facilitating seamless interaction with MongoDB databases, constructing robust internal or external APIs, establishing efficient TCP connections, and enabling real-time communication. Developed as a comprehensive wrapper around the Native Node.js MongoDB driver, it effectively streamlines the intricacies typically associated with this technology, as well as with Mongoose.js. Acting as a duplex stream, particularly a Transform stream, Model maximizes the potential of both the MongoDB driver and the Node.js Transform Stream API. Essentially, any task achievable with these cutting-edge technologies can be effortlessly accomplished using Model. Furthermore, Model operates with a strong emphasis on event-driven architecture and maintains impeccable compatibility with Mongoose.js, enhancing its overall versatility and usability.
Installation
$ yarn add @mongodb-model/model
or
$ npm i @mongodb-model/model
That's it: start using it!
Instantiate the Model class by providing an object with your database URL and collection name as keys. This will give you the corresponding collection model!
const Model = require('@mongodb-model/model');
const User = new Model({url: 'mongodb://localhost:27017/model', collection: 'users'});
By initializing the Model class, the database connection process is automated, eliminating the need for manual handling. The instantiation of the Model class seamlessly takes care of the database connection. Additionally, using a schema is entirely optional!
- CREATE
Use Promise
User.insertOne({firstname: 'John', lastname: 'Doe', email: '[email protected]', username: 'johndoe'}); .then(result => console.log('user inserted', result)) .catch(error => console.log('error inserting user', error));
Or Use Event
User.insertOne({firstname: 'John', lastname: 'Doe', email: '[email protected]', username: 'johndoe'}); User.on('insertOne', result => console.log('user inserted', result)); User.on('insertOne-error', error => console.log('error inserting user', error));
Or Use Callback
User.insertOne({firstname: 'John', lastname: 'Doe', email: '[email protected]', username: 'johndoe'},{},(error, users) => { if(error) return console.log('error inserting user', error); console.log('user inserted', result); });
- READ
Use Promise
User.find() .then(users => console.log('users found', users)) .catch(error => console.log('error finding users', error));
Or Use Event
User.find(); User.on('find', users => console.log('users found', users)); User.on('find-error', users => console.log('error finding users', users));
Or Use Callback
User.find({},{},(error, users) => { if(error) return console.log('error finding users', error); console.log('users found', users); });
- UPDATE
Use Promise
User.updateOne({username: 'johndoe'},{email: '[email protected]'}) .then(result => console.log('user updated', result)) .catch(error => console.log('error updating', error));
Or Use Event
User.updateOne({username: 'johndoe'},{email: '[email protected]'}); User.on('updateOne', result => console.log('user updated', result)); User.on('updateOne-error', error => console.log('error updating', error));
Or Use Callback
User.updateOne({username: 'johndoe'},{email: '[email protected]'},{},(error, result) => { if(error) return console.log('error updating', error); console.log('user updated', result); });
- DELETE
Use Promise
User.deleteOne({username: 'johndoe'}) .then(result => console.log('user deleted', result)) .catch(error => console.log('error deleting user', error));
Or Use Event
User.deleteOne({username: 'johndoe'}); User.on('deleteOne', result => console.log('user deleted', result)); User.on('deleteOne-error', error => console.log('error deleting user', error));
Or Use Callback
User.deleteOne({username: 'johndoe'},{},(error, result) => { if(error) return console.log('error deleting user', error); console.log('user deleted', result); });
A MORE DETAILED EXPLANATION
1. add .env file in your project root directory with these environment variables (at least the first two: DATABASE_NAME and DATABASE_URL, DATABASE_)
*** No need for installing dotenv npm package ***
DATABASE_NAME='Your Mongodb Database Name'
DATABASE_URL='Your Mongodb Database URL'
JSON_FAKER_URL='Your json faker url'
BUCKET_NAME='Your GridFS bucket name'
Here is an example:
DATABASE_NAME='my_app'
DATABASE_URL='mongodb://localhost:27017'
JSON_FAKER_URL='https://jsonplaceholder.typicode.com/'
BUCKET_NAME='myGridFSBucket'
2. Make sure you have mongodb server running if you are using mongodb server locally.
NOTE: The .env file is not required. It is completely optional. It only helps instantiate the MongoDB Model by passing the object with only one key: the collection name as shown in the rest of this documentation.
Start using it
Mongodb-model leverages the power of the MongoDB Native Node.js Driver, simplifying its complexities. It utilizes the same set of methods with identical parameters, seamlessly integrating with the Mongodb Native Node.js Driver. When employing the callback style, an additional callback function is included for flexibility.
Usage
Simply initialize the Model class. This automates the database connection process. There's no need for manual database connection handling, as it is seamlessly taken care of during the instantiation of the Model class.
const Model = require('@mongodb-model/model');
const ModelName = new Model({collection: 'collectionName'});
Depending on your requirements, you have the flexibility to opt for one or a combination of three approaches: the promise approach, the event approach, and the callback approach. By leveraging these approaches, you can effectively address various scenarios and accomplish your goals. The versatility provided by these options empowers you to tailor your solution to meet your specific needs. Embracing the simplicity and power of these approaches, you can confidently navigate your development journey.
Using Promise
ModelName.methodName(parameter1, parameter2, ...) .then(result => /** Your success codes here**/) .catch(error => /** Your error codes here**/);
Using Event
ModelName.methodName(parameter1, parameter2, ...); ModelName.on('methodName', result => /** Your success codes here**/); ModelName.on('methodName-error', error => /** Your error codes here**/);
Using Callback: all parameters are required (not optional) when using the callback approach.
ModelName.methodName(parameter1, parameter2, ...,(error, result) => { /** Your successs and error codes here**/ });
That's all there is! It's that simple!
Examples
The following examples showcase mongodb-model capabilities.
const Model = require('@mongodb-model/model');
const User = new Model({collection: 'users'});
Find all users
Using Promise
User.find() .then(users => console.log('all users found', users)) .catch(error => console.log('error finding all users', error));
Using Event
User.find(); User.on('find', users => console.log('all users found', users)); User.on('find-error', users => console.log('error finding all users', users));
Using Callback
User.find({},{},(error, users) => { if(error) return console.log('error finding all users', error); console.log('all users found', users); });
Find or retrieve all users based on their last name while excluding their _ids and usernames
Using Promise
User.find({lastname: 'Doe'}, {projection: {_id: 0, username: 0}}) .then(users => console.log('all users found', users)) .catch(error => console.log('error finding all users', error));
Using Event
User.find({lastname: 'Doe'}, {projection: {_id: 0, username: 0}}); User.on('find', users => console.log('all users found', users)); User.on('find-error', users => console.log('error finding all users', users));
Using Callback
User.find({lastname: 'Doe'}, {projection: {_id: 0, username: 0}},(error, users) => { if(error) return console.log('error finding all users', error); console.log('all users found', users); });
Find or retrieve all users based on their last name while excluding all other fields except their _id, first names, last names, emails, and phones
Using Promise
const options = {projection: {firstname: 1, lastname: 1, email: 1, phone: 1}}; User.find({lastname: 'Doe'}, options) .then(users => console.log('all users found', users)) .catch(error => console.log('error finding all users', error));
Using Event
const options = {projection: {firstname: 1, lastname: 1, email: 1, phone: 1}}; User.find({lastname: 'Doe'}, options); User.on('find', users => console.log('all users found', users)); User.on('find-error', users => console.log('error finding all users', users));
Using Callback
const options = {projection: {firstname: 1, lastname: 1, email: 1, phone: 1}}; User.find({lastname: 'Doe'}, options,(error, users) => { if(error) return console.log('error finding all users', error); console.log('all users found', users); });
Find or retrieve all users based on their last name, excluding all other fields except _id, first names, last names, emails, and phones. Additionally, sort the results by _id in descending order to obtain a desired sorting arrangement
Using Promise
const options = {projection: {firstname: 1, lastname: 1, email: 1, phone: 1, sort: {_id: -1}}}; User.find({lastname: 'Doe'}, options) .then(users => console.log('all users found', users)) .catch(error => console.log('error finding all users', error));
Using Event
const options = {projection: {firstname: 1, lastname: 1, email: 1, phone: 1, sort: {_id: -1}}}; User.find({lastname: 'Doe'}, options); User.on('find', users => console.log('all users found', users)); User.on('find-error', users => console.log('error finding all users', users));
Using Callback
const options = {projection: {firstname: 1, lastname: 1, email: 1, phone: 1, sort: {_id: -1}}}; User.find({lastname: 'Doe'}, options,(error, users) => { if(error) return console.log('error finding all users', error); console.log('all users found', users); });
Basic CRUD (Create, Read, Update, Delete)
Mongodb-model is designed to harness the full potential of the MongoDB Native Node.js Driver while offering a simplified experience. It seamlessly incorporates the underlying Mongodb Native Node.js Driver, offering an identical set of methods with consistent parameters. Moreover, when employing the callback style, Mongodb-model conveniently includes an extra callback function to facilitate seamless integration. With Mongodb-model, you can leverage the power of the MongoDB Native Node.js Driver without compromising on ease of use or functionality.
CREATE
- Using Promise
Using the create method
const userData = {firstname: 'John', lastname: 'Doe'}; User.create(userData) .then(result => console.log('user created successfully:' + result)); .catch(err => console.log('error creating user: ' + err));
Using the insertOne Method
const userData = {firstname: 'John', lastname: 'Doe'}; User.insertOne(userData). .then(result => console.log('user created successfully')); .catch(err => console.log('error creating user: ' + err));
- Using Callback
Using the create method
const userData = {firstname: 'John', lastname: 'Doe'}; User.create(userData,{},(error, result) => { if(error) return console.log('error creating user', result); console.log('created user', result); })
Using the insertOne Method
const userData = {firstname: 'John', lastname: 'Doe'}; User.insertOne(userData,{},(error, result) => { if(error) return console.log('error creating user', result); console.log('created user', result); })
- Using Event
Using the create method
const userData = {firstname: 'John', lastname: 'Doe'}; User.create(userData); User.on('create', user => console.log('user created', user)); User.on('create-error', error => console.log('error creating user', error));
Using the insertOne Method
const userData = {firstname: 'John', lastname: 'Doe'}; User.insertOne(userData); User.on('insertOne', user => console.log('user inserted', user)); User.on('insertOne-error', error => console.log('error inserting user', error));
READ
- Using Promise
Using the all method
User.all() .then(users => console.log('users found', users)) .catch(error => console.log('error finding users', error));
Using the find Method
User.find() .then(users => console.log('users found', users)) .catch(error => console.log('error finding users', error));
Using the findById Method
User.findById('645e4d81c050a750429b4421') .then(user => console.log('user by id', user)) .catch(error => console.log('error finding user by id', error));
Using the lastByEmail Method
User.lastByEmail('[email protected]') .then(user => console.log('last user by email found', user)) .catch(error => console.log('error finding last user by email', error));
- Using Callback
Using the all method
User.all({},{},(error, users) => { if(error) return console.log('error getting users', error); console.log('all users', users); })
Using the find Method
User.find({},{},(error, users) => { if(error) return console.log('error finding users', error); console.log('all users', users); })
Using the findById method
User.findById('645e4d81c050a750429b4421',{},(error, user) => { if(error) return console.log('error finding user by id', error); console.log('found user by id', user); })
Using the lastByEmail Method
User.lastByEmail('[email protected]',{},(error, user) => { if(error) return console.log('error finding last user by email', error); console.log('last user by email found', user); });
- Using Event
Using the all method
User.all(); User.on('all', users => console.log('all users', users)); User.on('all-error', error => console.log('error getting all users', error));
Using the find Method
User.find(); User.on('find', users => console.log('all found users', users)); User.on('find-error', error => console.log('error finding users', error));
Using the findById method
User.findById('645e4d81c050a750429b4421'); User.on('findById', user => console.log(user)); User.on('findById-error', error => console.log(error));
Using the lastByEmail Method
User.lastByEmail('[email protected]'); User.on('lastByEmail', user => console.log(user)); User.on('lastByEmail-error', error => console.log(error));
UPDATE
- Using Promise
Using the update method
const filter = {_id: '645e4d81c050a750429b4421'}; const update = {firstname: 'John', lastname: 'Doe'}; User.update(filter, update) .then(result => console.log('updated user', result)) .catch(error => console.log('error updating user', error));
Using the updateOne Method
const filter = {_id: '645e4d81c050a750429b4421'}; const update = {firstname: 'John', lastname: 'Doe'}; User.updateOne(filter, update) .then(result => console.log('updated user', result)) .catch(error => console.log('error updated user', error));
Using the updateMany Method
const filterForMany = {lastname: 'DeMaison'}; const updateForMany = {firstname: 'André De', lastname: 'Maison'}; User.updateMany(filterForMany, updateForMany) .then(result => console.log('updated users', result)) .catch(error => console.log('error updated users', error));
Using the updateById Method
const update = {firstname: 'John', lastname: 'Doe'}; User.updateById('645e4d81c050a750429b4421', update) .then(result => console.log('updated user', result)) .catch(error => console.log('error updated user', error));
- Using Callback
Using the update method
const filter = {_id: '645e4d81c050a750429b4421'}; const update = {firstname: 'John', lastname: 'Doe'}; User.update(filter, update, {}, (error, result) => { if(error) return console.log('error updating user', result); console.log('updated user', result); });
Using the updateOne Method
const filter = {_id: '645e4d81c050a750429b4421'}; const update = {firstname: 'John', lastname: 'Doe'}; User.updateOne(filter, update, {}, (error, result) => { if(error) return console.log('error updating user', result); console.log('updated user', result); });
Using the updateMany method
const filterForMany = {lastname: 'DeMaison'}; const updateForMany = {firstname: 'André De', lastname: 'Maison'}; User.updateMany(filterForMany, updateForMany, {},(error, result) => { if(error) return console.log('error updating users', result); console.log('updated users', result); });
Using the updateById Method
const update = {firstname: 'John', lastname: 'Doe'}; User.updateById('645e4d81c050a750429b4421',{},(error, result) => { if(error) return console.log('error updating last user by id', error); console.log('user updated by id', result); });
- Using Event
Using the update method
const filter = {_id: '645e4d81c050a750429b4421'}; const update = {firstname: 'John', lastname: 'Doe'}; User.update(filter, update); User.on('update', user => console.log('updated user', user)); User.on('update-error', error => console.log('error updating user', error));
Using the updateOne Method
const filter = {_id: '645e4d81c050a750429b4421'}; const update = {firstname: 'John', lastname: 'Doe'}; User.updateOne(filter, update); User.on('updateOne', user => console.log('updated user', user)); User.on('updateOne-error', error => console.log('error updating user', error));
Using the updateMany method
const filterForMany = {lastname: 'DeMaison'} const updateForMany = {firstname: 'André De', lastname: 'Maison'}; User.updateMany(filterForMany, updateForMany); User.on('updateMany', result => console.log('updated users', result)); User.on('updateMany-error', error => console.log('error updating users', error));
Using the updateById Method
const update = {firstname: 'John', lastname: 'Doe'}; User.updateById('645b9cf776b7fb46975316d9', update) User.on('updateById', result => console.log('updated user by id', result)); User.on('updateById-error', error => console.log('error updating user by id', error));
DELETE
Using Promise
Using the destroy method
User.destroy({username: 'johndoe'}) .then(result => console.log('user destroyed', result)) .catch(error => console.log('error destroying user', error));
Using the remove method
User.remove({username: 'johndoe'}) .then(result => console.log('user removed', result)) .catch(error => console.log('error removining user', error));
Using the deleteOne Method
User.deleteOne({username: 'johndoe'}) .then(result => console.log('user deleted', result)) .catch(error => console.log('error deleting user', error));
Using the updateMany Method
User.deleteMany({username: 'johndoe'}) .then(result => console.log('users deleted', result)) .catch(error => console.log('error deleting users', error));
Using the deleteById Method
User.deleteById('645b9cf776b7fb46975316d9') .then(user => console.log('user deleted by id', user)) .catch(error => console.log('error deleting user by id', error));
Using the removeById Method
User.removeById('645b9cf776b7fb46975316d9') .then(user => console.log('user removed by id', user)) .catch(error => console.log('error removing user by id', error));
Using the deleteByEmail Method
User.deleteByEmail('[email protected]') .then(user => console.log('user deleted by email', user)) .catch(error => console.log('error deleting user by email', error));
Using the deleteByUsername Method
User.deleteByUsername('johndoe') .then(user => console.log('user deleted by username', user)) .catch(error => console.log('error deleting user by username', error));
Using Callback
Using the destroy method
User.destroy({username: 'johndoe'},{}, (error,result) => { if(error) console.log('error destroying user', error); console.log('user deleted', result); })
Using the remove method
User.remove({username: 'johndoe'},{}, (error,result) => { if(error) console.log('error removing user', error); console.log('user removed', result); })
Using the deleteOne Method
User.deleteOne({username: 'johndoe'},{},(error, result) => { if(error) console.log('error deleting user', error); console.log('user deleted', result); })
Using the deleteMany Method
User.deleteMany({username: 'johndoe'},{}, (error, result) =>{ if(error) console.log('error deleting users', error); console.log('users deleted', result); })
Using the deleteById Method
User.deleteById('645b9cf776b7fb46975316d9', {}, (error, result) =>{ if(error) console.log('error deleting user by id', error); console.log('user deleted by id', result); })
Using the removeById Method
User.removeById('645b9cf776b7fb46975316d9', {}, (error, result) =>{ if(error) console.log('error removing user by id', error); console.log('user removed by id', result); })
Using the deleteByEmail Method
User.deleteByEmail('[email protected]', {}, (error, result) =>{ if(error) console.log('error deleting user by email', error); console.log('user deleted by email', result); })
Using the deleteByUsername Method
User.deleteByUsername('johndoe', {}, (error, result) =>{ if(error) console.log('error deleting user by username', error); console.log('user deleted by username', result); })
Using Event
Using the destroy method
User.destroy({username: 'johndoe'}); User.on('delete', result => console.log('user destroyed', result)); User.on('delete-error', error => console.log('error destroying user', error));
Using the remove method
User.remove({username: 'johndoe'}); User.on('delete', result => console.log('user removed', result)); User.on('delete-error', error => console.log('error removing user', error));
Using the deleteOne Method
User.deleteOne({username: 'johndoe'}); User.on('deleteOne',result => console.log('user deleted', result)); User.on('deleteOne-error',error => console.log('error deleting user', error));
Using the deleteMany Method
User.deleteMany({username: 'johndoe'}); User.on('deleteMany', result => console.log('user deleted', result)); User.on('deleteMany-error', error => console.log('error deleting user', error));
Using the deleteById Method
User.deleteById('645b9cf776b7fb46975316d9'); User.on('deleteById',result => console.log('user deleted', result)); User.on('deleteById-error',error => console.log('error deleting user', error));
Using the removeById Method
User.removeById('645b9cf776b7fb46975316d9'); User.on('removeById',result => console.log('user removed by id', result)); User.on('removeById-error',error => console.log('error removing user by id', error));
Using the deleteByEmail Method
User.deleteByEmail('[email protected]'); User.on('deleteByEmail',result => console.log('user deleted by email', result)); User.on('deleteByEmail-error',error => console.log('error deleting user by email', error));
Using the deleteByUsername Method
User.deleteByUsername('johndoe'); User.on('deleteByUsername', result => console.log('user deleted by username', result)); User.on('deleteByUsername-error', error => console.log('error deleting user by username', error));
Using it in a framework
Integrating the Mongodb Model into your application framework brings numerous benefits. It allows you to leverage the flexibility and scalability of MongoDB while seamlessly integrating with your existing application infrastructure.
By incorporating the Mongodb Model, you can take advantage of its intuitive methods and functions for data management. It provides an organized approach to defining models, handling data validations, and performing CRUD operations, making it easier to work with MongoDB within the context of your application framework.
Using it in Express
Setting up a simple express server
const express = require('express');
const Model = require('@mongodb-model/model');
const app = express();
app.use(express.json());
const User = new Model({collection: 'users'});
/**
Each of the example codes for the remaining of this section will go right here.
**/
app.listen(3000, () => console.log('listening on port 3000'));
CREATE
Using Promise
Using the create method
app.post('/users', async (req, res, next) => { try{ const result = await User.create(req.body); res.status(200).send({result}); }catch(error){ res.status(500).send({error}); } });
Using the insertOne method
app.post('/users', async (req, res, next) => { try{ const result = await User.insertOne(req.body); res.status(200).send({result}); }catch(error){ res.status(500).send({error}); } });
Using Callback
Using the create method
app.post('/users', (req, res, next) => { User.create(req.body,{},(error, result) => { if(error) return res.status(500).send({error}); res.status(200).send({result}); }); });
Using the insertOne method
app.post('/users', (req, res, next) => { User.insertOne(req.body,{},(error, result) => { if(error) return res.status(500).send({error}); res.status(200).send({result}); }); });
Using Event
Using the create method
app.post('/users', (req, res, next) => { User.create(req.body); User.on('create', result => res.status(200).send({result})); User.on('create-error', error => res.status(500).send({error})); });
Using the insertOne method
app.post('/users', (req, res, next) => { User.insertOne(req.body); User.on('insertOne', result => res.status(200).send({result})); User.on('insertOne-error', error => res.status(500).send({error})); });
READ
Using Promise
Using the all method
app.get('/users', async (req, res, next) => { try{ const users = await User.all(); res.status(200).send(users); }catch(error){ res.status(500).send({error}); } });
Using the find method
app.get('/users', async (req, res, next) => { try{ const users = await User.find(); res.status(200).send(users); }catch(error){ res.status(500).send({error}); } });
Using the findById method
app.get('/users/:id', async (req, res, next) => { try{ const user = await User.findById(req.params.id); res.status(200).send(user); }catch(error){ res.status(500).send({error}); } });
Using the findByEmail method
app.get('/user-email', async (req, res, next) => { try{ const user = await User.findByEmail(req.body.email); res.status(200).send(user); }catch(error){ res.status(500).send({error}); } });
Using Callback
Using the all method
app.get('/users', (req, res, next) => { User.all({},{},(error, users) => { if(error) return res.status(500).send({error}); res.status(200).send(users); }); });
Using the find method
app.get('/users', (req, res, next) => { User.find({},{},(error, users) => { if(error) return res.status(500).send({error}); res.status(200).send(users); }); });
Using the findById method
app.get('/users/:id', (req, res, next) => { User.findById(req.params.id,{},(error, user) => { if(error) return res.status(500).send({error}); res.status(200).send(user); }); });
Using the findByEmail method
app.get('/user-email', (req, res, next) => { User.findByEmail(req.body.email,{},(error, user) => { if(error) return res.status(500).send({error}); res.status(200).send(user); }); });
Using Event
Using the all method
app.get('/users', (req, res, next) => { User.all(); User.on('all', result => res.status(200).send(users)); User.on('all-error', error => res.status(500).send({error})); });
Using the find method
app.get('/users', (req, res, next) => { User.find(); User.on('find', users => res.status(200).send(users)); User.on('find-error', error => res.status(500).send({error})); });
Using the findById method
app.get('/users/:id', (req, res, next) => { User.findById(req.params.id); User.on('findById', user => res.status(200).send(user)); User.on('findById-error', error => res.status(500).send({error})); });
Using the findByEmail method
app.get('/user-email', (req, res, next) => { User.findByEmail(req.body.email); User.on('findByEmail', user => res.status(200).send(user)); User.on('findByEmail-error', error => res.status(500).send({error})); });
UPDATE
Using Promise
Using the update method
app.put('/users/:id', async (req, res, next) => { try{ const userId = User.objectId(req.params.id); const updated = await User.update({_id: userId},req.body); res.status(200).send({updated}); }catch(error){ res.status(500).send({error}); } });
Using the updateById method
app.put('/users/:id', async (req, res, next) => { try{ const updated = await User.updateById(req.params.id, req.body); res.status(200).send({updated}); }catch(error){ res.status(500).send({error}); } });
Using the updateByUsername method
app.put('/user-username', async (req, res, next) => { try{ const updated = await User.updateByUsername(req.body.username, req.body); res.status(200).send({updated}); }catch(error){ res.status(500).send({error}); } });
Using the updateByEmail method
app.put('/user-email', async (req, res, next) => { try{ const updated = await User.updateByEmail(req.body.email, req.body); res.status(200).send({updated}); }catch(error){ res.status(500).send({error}); } });
Using Callback
Using the create method
app.post('/users', (req, res, next) => { User.create(req.body,{},(error, result) => { if(error) return res.status(500).send({error}); res.status(200).send({result}); }); });
Using the insertOne method
app.post('/users', (req, res, next) => { User.insertOne(req.body,{},(error, result) => { if(error) return res.status(500).send({error}); res.status(200).send({result}); }); });
Using Event
Using the create method
app.post('/users', (req, res, next) => { User.create(req.body); User.on('create', result => res.status(200).send({result})); User.on('create-error', error => res.status(500).send({error})); });
Using the insertOne method
app.post('/users', (req, res, next) => { User.insertOne(req.body); User.on('insertOne', result => res.status(200).send({result})); User.on('insertOne-error', error => res.status(500).send({error})); });
DELETE
Using Promise
Using the deleteOne method
app.delete('/users/:id', async (req, res, next) => { try{ const userId = User.objectId(req.params.id); const result = await deleteOne({_id: userId}); res.status(200).send({result}); }catch(error){ res.status(500).send({error}); } });
Using the destroy method
app.delete('/users/:id', async (req, res, next) => { try{ const userId = User.objectId(req.params.id); const result = await destroy({_id: userId}); res.status(200).send(result); }catch(error){ res.status(500).send({error}); } });
Using the deleteById method
app.delete('/users/:id', async (req, res, next) => { try{ const result = await deleteById(req.params.id); res.status(200).send(result); }catch(error){ res.status(500).send({error}); } });
- Using the remove method
app.delete('/users/:id', async (req, res, next) => { try{ const userId = User.objectId(req.params.id); const result = await remove({_id: userId}); res.status(200).send(result); }catch(error){ res.status(500).send({error}); } });
Using the deleteByEmail method
app.delete('/delete-user-by-email', async (req, res, next) => { try{ const result = await User.deleteByEmail(req.body.email); res.status(200).send({result}); }catch(error){ res.status(500).send({error}); } });
Using Callback
Using the deleteOne method
app.delete('/users/:id', (req, res, next) => { const userId = User.objectId(req.params.id); User.deleteOne({_id: userId},{}, (error,result) => { if(error) console.log('error deleting user', error); console.log('user deleted', result); }); });
Using the destroy method
app.delete('/users/:id', (req, res, next) => { const userId = User.objectId(req.params.id); User.destroy({_id: userId},{}, (error,result) => { if(error) console.log('error deleting user', error); console.log('user deleted', result); }); });
Using the deleteById method
app.delete('/users/:id', (req, res, next) => { User.deleteById(req.params.id,{}, (error,result) => { if(error) console.log('error deleting user', error); console.log('user deleted', result); }); });
Using the remove method
app.delete('/users/:id', (req, res, next) => { const userId = User.objectId(req.params.id); User.remove({_id: userId},{}, (error,result) => { if(error) console.log('error deleting user', error); console.log('user deleted', result); }); });
Using the deleteByEmail method
app.delete('/delete-user-by-email', (req, res, next) => { const userId = User.objectId(req.params.id); User.deleteByEmail(req.body.email,{}, (error,result) => { if(error) console.log('error deleting user', error); console.log('user deleted', result); }); });
Using Event
Using the deleteOne method
app.delete('/users/:id', (req, res, next) => { const userId = User.objectId(req.params.id); User.deleteOne({_id: userId}); User.on('deleteOne', result => console.log('user deleted', result)); User.on('deleteOne-error', error => console.log('error user deleting user', error)); });
Using the destroy method
app.delete('/users/:id', (req, res, next) => { const userId = User.objectId(req.params.id); User.destroy({_id: userId}); User.on('destroy', result => console.log('user destroyed', result)); User.on('destroy-error', error => console.log('error user destroying user', error)); });
Using the deleteById method
app.delete('/users/:id', (req, res, next) => { const userId = User.objectId(req.params.id); User.deleteById(req.params.id); User.on('deleteById', result => console.log('user deleted by id', result)); User.on('deleteById-error', error => console.log('error deleting user by id', error)); });
Using the remove method
app.delete('/users/:id', (req, res, next) => { const userId = User.objectId(req.params.id); User.remove({_id: userId}); User.on('remove', result => console.log('user removed', result)); User.on('remove-error', error => console.log('error user removing user', error)); });
Using the deleteByEmail method
app.delete('/delete-user-by-email', (req, res, next) => { User.deleteByEmail(req.body.email); User.on('deleteByEmail', result => console.log('user deleted by email', result)); User.on('deleteByEmail-error', error => console.log('error user deleting user by email', error)); });
Making HTTP/HTTPS Requests: Internal/External API calls
In today's interconnected world, applications often need to interact with external services and APIs to retrieve or manipulate data. Whether it's fetching weather information, integrating with social media platforms, or accessing internal microservices, the ability to make HTTP/HTTPS requests is a crucial aspect of modern application development.
With mongodb-model, developers can harness the power of MongoDB's document-based data model while effortlessly integrating with various APIs to create dynamic and data-driven experiences.
This section explores the mechanisms and best practices for making HTTP/HTTPS requests within the mongodb-model framework. We will delve into topics such as performing CRUD operations on external resources, handling authentication and authorization, managing request timeouts and retries, and efficiently processing API responses. By understanding these concepts, developers can extend the capabilities of their mongodb-model applications and leverage the vast array of services available through APIs. So, let's dive into the world of making HTTP/HTTPS requests with mongodb-model and unlock the potential for building truly interconnected applications.
To begin, we initialize the Model class, which automatically establishes a connection with the database. Hence, manual database connection becomes unnecessary as it is handled by the instantiation process itself.
const Model = require('@mongodb-model/model');
const User = new Model({collection: 'users'});
Usage
HTTPS
get
- Using promise
User.get('api_endpoint_https_url') .then(response => /** Your response codes here**/) .catch(error => /** Your error codes here**/);
- Using Callback
User.get('api_endpoint_https_url', (error, result) => { /** Your success and error codes here**/ });
- Using Event
User.get('api_endpoint_https_url'); User.on('get', result => /** Your success codes here**/); User.on('get-error', error => /** Your error codes here**/);
- Using promise
post
- Using promise
User.post('api_endpoint_https_url', postData) .then(response => /** Your response codes here**/) .catch(error => /** Your error codes here**/);
- Using Callback
User.post('api_endpoint_https_url', postData, (error, result) => { /** Your success and error codes here**/ });
- Using Event
User.post('api_endpoint_https_url', postData); User.on('post', result => /** Your success codes here**/); User.on('post-error', error => /** Your error codes here**/);
- Using promise
put
- Using promise
User.put('api_endpoint_https_url', updateData) .then(response => /** Your response codes here**/) .catch(error => /** Your error codes here**/);
- Using Callback
User.put('api_endpoint_https_url', updateData,(error, result) => { /** Your success and error codes here**/ });
- Using Event
User.put('api_endpoint_https_url', updateData); User.on('put', result => /** Your success codes here**/); User.on('put-error', error => /** Your error codes here**/);
- Using promise
delete
- Using promise
User.delete('api_endpoint_https_url') .then(response => /** Your response codes here**/) .catch(error => /** Your error codes here**/);
- Using Callback
User.delete('api_endpoint_https_url', (error, result) => { /** Your success and error codes here**/ });
- Using Event
User.delete('api_endpoint_https_url'); User.on('delete', result => /** Your success codes here**/); User.on('delete-error', error => /** Your error codes here**/);
- Using promise
HTTP
GET
- Using promise
User.GET('api_endpoint_http_url') .then(response => /** Your response codes here**/) .catch(error => /** Your error codes here**/);
- Using Callback
User.GET('api_endpoint_http_url', (error, result) => { /** Your success and error codes here**/ });
- Using Event
User.GET('api_endpoint_http_url'); User.on('GET', result => /** Your success codes here**/); User.on('GET-error', error => /** Your error codes here**/);
- Using promise
POST
- Using promise
User.POST('api_endpoint_http_url', postData) .then(response => /** Your response codes here**/) .catch(error => /** Your error codes here**/);
- Using Callback
User.POST('api_endpoint_http_url', postData, (error, result) => { /** Your success and error codes here**/ });
- Using Event
User.POST('api_endpoint_http_url', postData); User.on('POST', result => /** Your success codes here**/); User.on('POST-error', error => /** Your error codes here**/);
- Using promise
PUT
- Using promise
User.PUT('api_endpoint_http_url', updateData) .then(response => /** Your response codes here**/) .catch(error => /** Your error codes here**/);
- Using Callback
User.PUT('api_endpoint_http_url', updateData,(error, result) => { /** Your success and error codes here**/ });
- Using Event
User.PUT('api_endpoint_http_url', updateData); User.on('PUT', result => /** Your success codes here**/); User.on('PUT-error', error => /** Your error codes here**/);
- Using promise
DELETE
- Using promise
User.DELETE('api_endpoint_http_url') .then(response => /** Your response codes here**/) .catch(error => /** Your error codes here**/);
- Using Callback
User.DELETE('api_endpoint_http_url', (error, result) => { /** Your success and error codes here**/ });
- Using Event
User.DELETE('api_endpoint_http_url'); User.on('DELETE', result => /** Your success codes here**/); User.on('DELETE-error', error => /** Your error codes here**/);
- Using promise
Examples
We will use the following example data for POST and PUT requests throughout the remain of this section:
const data = {
postId: 20,
name: 'laudantium delectus nam',
email: '[email protected]',
body: 'NEW POST aut quam consequatur sit et\n' +
'repellat maiores laborum similique voluptatem necessitatibus nihil\n' +
'et debitis nemo occaecati cupiditate\n' +
'modi dolorum quia aut'
}
HTTPS
get: perform a GET request to 'https://jsonplaceholder.typicode.com/comments'
- Using promise
User.get('https://jsonplaceholder.typicode.com/comments') .then(response => console.log(response)) .catch(error => console.log(error));
- Using Callback
User.get('https://jsonplaceholder.typicode.com/comments', (error, result) => { if(error) return console.log(error); console.log(result); });
- Using Event
User.get('https://jsonplaceholder.typicode.com/comments'); User.on('get', result => console.log(result)); User.on('get-error', error => console.log(error));
- Using promise
post: perform a POST request to 'https://jsonplaceholder.typicode.com/comments'
- Using promise
User.post('https://jsonplaceholder.typicode.com/comments', data) .then(response => console.log(response)) .catch(error => console.log(error));
- Using Callback
User.post('https://jsonplaceholder.typicode.com/comments', data, (error, result) => { if(error) return console.log(error); console.log(result); });
- Using Event
User.post('https://jsonplaceholder.typicode.com/comments', data); User.on('post', result => console.log(result)); User.on('post-error', error => console.log(error));
- Using promise
put: perform a PUT request to 'https://jsonplaceholder.typicode.com/comments/1'
- Using promise
User.put('https://jsonplaceholder.typicode.com/comments/1', data) .then(response => console.log(response)) .catch(error => console.log(error));
- Using Callback
User.put('https://jsonplaceholder.typicode.com/comments/1', data, (error, result) => { if(error) return console.log(error); console.log(result); });
- Using Event
User.put('https://jsonplaceholder.typicode.com/comments/1', data); User.on('put', result => console.log(result)); User.on('put-error', error => console.log(error));
- Using promise
delete: perform a DELETE request to 'https://jsonplaceholder.typicode.com/comments/1
- Using promise
User.delete('https://jsonplaceholder.typicode.com/comments/1') .then(response => console.log(response)) .catch(error => console.log(error));
- Using Callback
User.delete('https://jsonplaceholder.typicode.com/comments/1', (error, result) => { if(error) return console.log(error); console.log(result); });
- Using Event
User.delete('https://jsonplaceholder.typicode.com/comments/1'); User.on('delete', result => console.log(result)); User.on('delete-error', error => console.log(error));
- Using promise
HTTP
GET: perform a GET request to a local server 'http://localhost:3000/users'
- Using promise
User.GET('http://localhost:3000/users') .then(users => console.log(users)) .catch(error => console.log(error));
- Using Callback
User.GET('http://localhost:3000/users', (error, users) => { if(error) return console.log(error); console.log(users); });
- Using Event
User.GET('http://localhost:3000/users'); User.on('GET', users => console.log(users)); User.on('GET-error', error => console.log(error));
- Using promise
POST: Perform a POST request to a local server 'http://localhost:3000/users'
- Using promise
User.POST('http://localhost:3000/users', data) .then(result => console.log(result)) .catch(error => console.log(error));
- Using Callback
User.post('https://jsonplaceholder.typicode.com/comments', data, (error, result) => { if(error) return console.log(error); console.log(result); });
- Using Event
User.POST('http://localhost:3000/users', data); User.on('POST', result => console.log(result)); User.on('POST-error', error => console.log(error));
- Using promise
PUT: perform a PUT request to a local server 'http://localhost:3000/users/1'
- Using promise
User.PUT('http://localhost:3000/users/1', data) .then(result => console.log(result)) .catch(error => console.log(error));
- Using Callback
User.PUT('http://localhost:3000/users/1', data, (error, result) => { if(error) return console.log(error); console.log(result); });
- Using Event
User.put('https://jsonplaceholder.typicode.com/comments/1', data); User.on('put', result => console.log(result)); User.on('put-error', error => console.log(error));
- Using promise
DELETE: perform a DELETE request to a local server 'http://localhost:3000/users/1'
- Using promise
User.DELETE('http://localhost:3000/users/1') .then(result => console.log(result)) .catch(error => console.log(error));
- Using Callback
User.DELETE('http://localhost:3000/users/1', (error, result) => { if(error) return console.log(error); console.log(result); });
- Using Event
User.DELETE('http://localhost:3000/users/1'); User.on('DELETE', result => console.log(result)); User.on('DELETE-error', error => console.log(error));
- Using promise
Making TCP Requests
When working with Mongodb model, making TCP requests is a crucial aspect of communication between the client and the MongoDB server. TCP (Transmission Control Protocol) provides a reliable and ordered channel for transmitting data, ensuring the integrity and accuracy of the information exchanged.
With the Mongodb model, you can easily make TCP requests to perform various operations on the MongoDB database. Whether it's inserting new data, updating existing records, or querying for specific information, the framework provides intuitive methods and functions to interact with the database using TCP/IP protocols.
To begin, we initialize the Model class, which automatically establishes a connection with the database. Hence, manual database connection becomes unnecessary as it is handled by the instantiation process itself.
const Model = require('@mongodb-model/model');
const User = new Model({collection: 'users'});
Basics
Creating a TCP Server
Create a TCP server with Redis using the User model.
const server = User.createTCPServerWithRedis();
Listen for 'connection' event on the TCP server
server.on('connection', socket => { console.log('Client is ready!'); });
Start listening on a port. Port 8000 is used in this example
server.listen(8000);
Basic TCP Server Creation Full Code
// Import the Model module const Model = require('@mongodb-model/model'); // Create a new instance of Model for the 'users' collection const User = new Model({ collection: 'users' }); // Create a TCP server with Redis using the User model const server = User.createTCPServerWithRedis(); // Listen for 'connection' event on the TCP server server.on('connection', socket => { console.log('Client is ready!'); }); // Start listening on port 8000 server.listen(8000);
Creating a TCP Client
Create a TCP client for the server at 'http://localhost:8000'
const client = User.createTCPClient('http://localhost:8000');
Handle the 'connect' event when the client connects to the server
client.on('connect', () => { console.log('Connected to server'); });
Basic TCP Client Creation Full Code
// Import the Model module const Model = require('@mongodb-model/model'); // Create a new instance of Model for the 'users' collection const User = new Model({ collection: 'users' }); // Create a TCP client for the server at 'http://localhost:8000'; const client = User.createTCPClient('http://localhost:8000'); // Handle the 'connect' event when the client connects to the server client.on('connect', () => { console.log('Connected to server'); });
Example
TCP Server
Create a TCP server with Redis using the User model.
const server = User.createTCPServerWithRedis();
Function to handle socket event listener for finding models
/** * Registers a socket event listener for finding models. * @param {Socket} socket - The socket object * @param {string} [event='find'] - The event name * @param {Model} [Model=User] - The model class to perform the find operation on */ const onFind = (socket, event = 'find', Model = User) => socket.on(event, () => { // Find models Model.find(); // Handle 'find' event Model.on('find', models => socket.emit(`${Model.collection}-${event}-success`, models)); // Handle 'find-error' event Model.on('find-error', error => socket.emit(`${Model.collection}-${event}-error`, error)); // Handle 'find-done' event socket.on(`${event}-done`, () => console.log(`${Model.collection}-${event} done!`)); // Handle 'find-failed' event socket.on(`${event}-failed`, () => console.log(`${Model.collection}-${event} failed!`)); });
Function to handle socket event listener for finding a model by ID.
/** * Registers a socket event listener for finding a model by ID. * @param {Socket} socket - The socket object * @param {string} [event='findById'] - The event name * @param {Model} [Model=User] - The model class to perform the find operation on */ const onFindById = (socket, event = 'findById', Model = User) => socket.on(event, modelId => { //Find model by id Model.findById(modelId); // Handle 'findById' event Model.on('findById', model => socket.emit(`${Model.collection}-${event}-success`, model)); // Handle 'findById-error' event Model.on('findById-error', error => socket.emit(`${Model.collection}-${event}-error`, error)); // Handle 'findById-done' event socket.on(`${event}-done`, () => console.log(`${Model.collection}-${event} done!`)); // Handle 'findById-failed' event socket.on(`${event}-failed`, () => console.log(`${Model.collection}-${event} failed!`)); });
Function to handle socket event listener for creating a model.
/** * Registers a socket event listener for creating a model. * @param {Socket} socket - The socket object * @param {string} [event='create'] - The event name * @param {Model} [Model=User] - The model class to perform the create operation on */ const onCreate = (socket, event = 'create', Model = User) => socket.on(event, modelData => { // Create model Model.create(modelData); // Handle 'create' event Model.on('create', result => socket.emit(`${Model.collection}-${event}-success`, result)); // Handle 'create-error' event Model.on('creat-error', error => socket.emit(`${Model.collection}-${event}-error`, error)); // Handle 'create-done' event socket.on(`${event}-done`, () => console.l