npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

enixa

v1.1.1

Published

A Amazing easy usage MongoDb driver Co-powered by ~Atmosoft

Downloads

16

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:

  1. Set up the database connection:
const { connectToDatabase } = require('enixa');

const uri = 'your_mongodb_uri';
connectToDatabase(uri);
  1. 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);
  1. 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 with name and type 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

  1. Create a symlink for the enixa library: Navigate to the enixa directory and run:

    cd enixa
    npm link
  2. Link the enixa library in the enixa-usage project: Navigate to the enixa-usage directory and run:

    cd ../enixa-usage
    npm link enixa
  3. Install other dependencies:

    npm install
  4. Run the server:

    npm start
  5. 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.