enixa
v1.1.1
Published
A Amazing easy usage MongoDb driver Co-powered by ~Atmosoft
Downloads
3
Readme
enixa
Library
Project Structure
/enixa
├── node_modules/
├── config.js
├── index.js
├── package.json
├── README.md
/enixa-usage
├── node_modules/
├── public/
│ ├── index.html
│ ├── style.css
│ └── script.js
├── routes/
│ └── api.js
├── app.js
├── package.json
enixa/config.js
const mongoose = require('mongoose');
const connectToDatabase = async (uri) => {
try {
await mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });
console.log('Connected to MongoDB');
} catch (error) {
console.error('Error connecting to MongoDB:', error);
}
};
module.exports = connectToDatabase;
enixa/index.js
const mongoose = require('mongoose');
const connectToDatabase = require('./config');
const validTypes = ['String', 'Number', 'Date', 'Buffer', 'Boolean', 'Mixed', 'ObjectId', 'Array', 'Decimal128', 'Map'];
const createSchema = (fields) => {
const schemaDefinition = {};
fields.forEach(field => {
if (!validTypes.includes(field.type)) {
throw new Error(`Invalid type specified for field ${field.name}: ${field.type}`);
}
schemaDefinition[field.name] = { type: mongoose.Schema.Types[field.type] };
});
return new mongoose.Schema(schemaDefinition);
};
const initializeModel = (collectionName, schema) => {
return mongoose.model(collectionName, schema);
};
const createDocument = async (model, data) => {
const document = new model(data);
return await document.save();
};
const readDocuments = async (model, query = {}) => {
return await model.find(query);
};
const updateDocument = async (model, id, updateData) => {
return await model.findByIdAndUpdate(id, updateData, { new: true });
};
const deleteDocument = async (model, id) => {
return await model.findByIdAndDelete(id);
};
module.exports = {
connectToDatabase,
createSchema,
initializeModel,
createDocument,
readDocuments,
updateDocument,
deleteDocument
};
enixa/README.md
# Enixa
Enixa is a simple library for performing CRUD operations on MongoDB with user-defined schemas. It uses Mongoose to handle MongoDB interactions.
## Installation
First, install the library using npm:
```bash
npm install enixa
Usage
To use Enixa in your project, follow these steps:
- Set up the database connection:
const { connectToDatabase } = require('enixa');
const uri = 'your_mongodb_uri';
connectToDatabase(uri);
- Create a schema and model:
const { createSchema, initializeModel } = require('enixa');
const userSchema = createSchema([
{ name: 'name', type: 'String' },
{ name: 'email', type: 'String' },
{ name: 'age', type: 'Number' }
]);
const UserModel = initializeModel('User', userSchema);
- Perform CRUD operations:
const { createDocument, readDocuments, updateDocument, deleteDocument } = require('enixa');
const run = async () => {
// Create
const user = await createDocument(UserModel, { name: 'John Doe', email: '[email protected]', age: 30 });
console.log('Created User:', user);
// Read
const users = await readDocuments(UserModel);
console.log('All Users:', users);
// Update
const updatedUser = await updateDocument(UserModel, user._id, { age: 31 });
console.log('Updated User:', updatedUser);
// Delete
const deletedUser = await deleteDocument(UserModel, user._id);
console.log('Deleted User:', deletedUser);
};
run();
API
connectToDatabase(uri)
Connects to the MongoDB database.
uri
: MongoDB connection string.
createSchema(fields)
Creates a Mongoose schema.
fields
: Array of field definitions. Each field should be an object withname
andtype
properties.
initializeModel(collectionName, schema)
Initializes a Mongoose model.
collectionName
: Name of the MongoDB collection.schema
: Mongoose schema.
createDocument(model, data)
Creates a new document.
model
: Mongoose model.data
: Document data.
readDocuments(model, query)
Reads documents based on a query.
model
: Mongoose model.query
: Query object (optional).
updateDocument(model, id, updateData)
Updates a document by ID.
model
: Mongoose model.id
: Document ID.updateData
: Data to update.
deleteDocument(model, id)
Deletes a document by ID.
model
: Mongoose model.id
: Document ID.
### `enixa-usage` Project
#### `enixa-usage/package.json`
```json
{
"name": "enixa-usage",
"version": "1.0.0",
"main": "app.js",
"scripts": {
"start": "node app.js"
},
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"mongoose": "^8.5.1",
"enixa": "file:../enixa"
}
}
enixa-usage/app.js
const express = require('express');
const bodyParser = require('body-parser');
const { connectToDatabase } = require('enixa');
const apiRoutes = require('./routes/api');
const app = express();
const port = 3000;
const uri = 'your_mongodb_uri';
connectToDatabase(uri);
app.use(bodyParser.json());
app.use(express.static('public'));
app.use('/api', apiRoutes);
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
enixa-usage/routes/api.js
const express = require('express');
const { createSchema, initializeModel, createDocument, readDocuments, updateDocument, deleteDocument } = require('enixa');
const router = express.Router();
const userSchema = createSchema([
{ name: 'name', type: 'String' },
{ name: 'email', type: 'String' },
{ name: 'age', type: 'Number' }
]);
const UserModel = initializeModel('User', userSchema);
router.post('/create', async (req, res) => {
const user = await createDocument(UserModel, req.body);
res.send(user);
});
router.get('/read', async (req, res) => {
const users = await readDocuments(UserModel);
res.send(users);
});
router.put('/update/:id', async (req, res) => {
const updatedUser = await updateDocument(UserModel, req.params.id, req.body);
res.send(updatedUser);
});
router.delete('/delete/:id', async (req, res) => {
const deletedUser = await deleteDocument(UserModel, req.params.id);
res.send(deletedUser);
});
module.exports = router;
enixa-usage/public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Enixa App</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>Enixa CRUD Application</h1>
<form id="user-form">
<input type="text" id="name" placeholder="Name" required>
<input type="email" id="email" placeholder="Email" required>
<input type="number" id="age" placeholder="Age" required>
<button type="submit">Add User</button>
</form>
<div id="user-list"></div>
</div>
<script src="script.js"></script>
</body>
</html>
enixa-usage/public/style.css
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align
-items: center;
height: 100vh;
}
.container {
background: white;
padding: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 300px;
}
h1 {
text-align: center;
}
form {
display: flex;
flex-direction: column;
}
input, button {
margin-bottom: 10px;
}
#user-list {
margin-top: 20px;
}
enixa-usage/public/script.js
document.getElementById('user-form').addEventListener('submit', async (e) => {
e.preventDefault();
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const age = document.getElementById('age').value;
const response = await fetch('/api/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name, email, age })
});
const user = await response.json();
addUserToList(user);
e.target.reset();
});
async function fetchUsers() {
const response = await fetch('/api/read');
const users = await response.json();
users.forEach(addUserToList);
}
function addUserToList(user) {
const userList = document.getElementById('user-list');
const userDiv = document.createElement('div');
userDiv.className = 'user';
userDiv.innerHTML = `
<p>Name: ${user.name}</p>
<p>Email: ${user.email}</p>
<p>Age: ${user.age}</p>
<button onclick="deleteUser('${user._id}')">Delete</button>
`;
userList.appendChild(userDiv);
}
async function deleteUser(userId) {
await fetch(`/api/delete/${userId}`, {
method: 'DELETE'
});
document.location.reload();
}
fetchUsers();
Steps to Use npm link
Create a symlink for the
enixa
library: Navigate to theenixa
directory and run:cd enixa npm link
Link the
enixa
library in theenixa-usage
project: Navigate to theenixa-usage
directory and run:cd ../enixa-usage npm link enixa
Install other dependencies:
npm install
Run the server:
npm start
Access the application: Open your browser and go to
http://localhost:3000
.
This setup integrates the enixa
library with an HTML/CSS/JS frontend, providing a simple interface for creating, reading, and deleting users from a MongoDB database.