@mephisto5558/mongoose-db
v3.1.3
Published
A DB class for Mongoose/MongoDB with and without cache, with flattend access.
Downloads
232
Readme
Mongoose-DB
DB Module for Node.js using Mongoose and MongoDB
This module provides a DB
and a NoCacheDB
class for MongoDB operations. The operations include:
- Establishing a connection to a MongoDB instance.
- Performing CRUD operations (Create, Read, Update, Delete).
- Caching data for performance (use the NoCacheDB if you don't want a cache).
- Logging operations and values.
Installation
$ npm install @mephisto5558/mongoose-db
How to Use
1. Import the DB Module
First, you need to import the DB
module into your JavaScript file:
const { DB } = require('@mephisto5558/mongoose-db');
// or
import { DB } from '@mephisto5558/mongoose-db'
2. Initialize a New DB Instance
Create a new instance of the DB
class, providing a MongoDB connection string:
const db = await new DB().init('<your-mongodb-connection-string>');
Examples
Fetch All Data
Fetch all data from the database and cache it: Note that this is done automatically after creating a new instance.
await db.fetchAll();
console.log('All data fetched');
Fetch a Specific Collection
Fetch a specific collection from the database and cache it:
const data = await db.fetch('collection')
console.log('Fetched data:', data);
Get a Value from the Cache
const value = db.get('collection', 'key');
console.log('Value:', value);
key
can be a flattened key:
Value in Mongodb:
{
"key": "collection",
"value": {
"key": {
"subkey1": {
"subkey2": "value"
}
}
}
}
JS code:
const value = db.get('collection', 'key.subkey1.subkey2')
Set a Value in a Collection
Set a value in a specific collection, with an option to overwrite existing data:
It is strongly suggested to use DB#update
instead.
const newValue = db.set('collection', 'value', true);
console.log('New value:', newValue);
Update a Specific Value in a Collection
Update a specific value in a specific collection:
The key can be flattend, see DB#get
for more information.
const updatedValue = db.update('collection', 'key', 'new-value').
console.log('Updated value:', updatedValue);
Add a Value to a Collection
Add a value to an array, with an option to prevent duplicate entries (using a set in MongoDB):
The key can be flattend, see DB#get
for more information.
const updatedArray = db.push('collection', 'key', 'value');
console.log('Updated collection:', updatedCollection);
Delete a Value or a Whole Collection
Delete a specific value or a whole collection, if no key is provided. This returns false if the key did not exist:
The key can be flattend, see DB#get
for more information.
const success = db.delete('collection', 'key');
console.log('Deletion successfull:', success);