@omniasync/asyncdb
v1.0.0
Published
Client library for AsyncDB
Maintainers
Readme
AsyncDB like Client Library
A like ODM (Object Document Mapper) for AsyncDB, providing a familiar interface for Node.js developers.
Installation
npm install asyncdb-mongooseQuick Start
const asyncdb = require('asyncdb-mongoose');
// Connect to AsyncDB server
await asyncdb.connect('async://admin:admin@localhost:32015/myapp');
// Define a schema
const userSchema = new asyncdb.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
age: { type: Number, default: 0 },
active: { type: Boolean, default: true }
});
// Create a model
const User = asyncdb.model('User', userSchema);
// Create a new user
const user = new User({
name: 'John Doe',
email: '[email protected]',
age: 30
});
await user.save();
// Find users
const users = await User.find({ age: { $gt: 25 } });
console.log(users);
// Disconnect
asyncdb.disconnect();Connection
Connect to Server
const asyncdb = require('asyncdb-mongoose');
await asyncdb.connect('async://user:password@host:port/database');Connection URI format: async://username:password@host:port/database
Check Connection Status
if (asyncdb.isConnected()) {
console.log('Connected to AsyncDB');
}Disconnect
asyncdb.disconnect();Schema
Define a Schema
const userSchema = new asyncdb.Schema({
name: String,
email: { type: String, required: true },
age: { type: Number, default: 0 },
tags: [String],
metadata: Object
});Schema Types
String- Text dataNumber- Numeric dataBoolean- True/false valuesObject- Nested objectsArray- Arrays of any type[Type]- Array of specific type (e.g.,[String])
Schema Options
const schema = new asyncdb.Schema({
name: {
type: String,
required: true, // Field is required
default: 'Anonymous', // Default value
unique: true, // Must be unique
index: true // Create an index
}
});Virtuals
userSchema.virtual('fullName').get(function() {
return this.firstName + ' ' + this.lastName;
});Methods
// Instance method
userSchema.method('greet', function() {
console.log(`Hello, ${this.name}!`);
});
// Static method
userSchema.static('findByName', function(name) {
return this.find({ name });
});Hooks
// Pre hook
userSchema.pre('save', function(next) {
console.log('About to save user');
next();
});
// Post hook
userSchema.post('save', function(doc) {
console.log('User saved:', doc.name);
});Models
Create a Model
const User = asyncdb.model('User', userSchema);Create a Document
const user = new User({
name: 'John Doe',
email: '[email protected]'
});
await user.save();Or using the static method:
const user = await User.create({
name: 'John Doe',
email: '[email protected]'
});Find Documents
// Find all
const users = await User.find();
// Find with filter
const activeUsers = await User.find({ active: true });
// Find with comparison operators
const adults = await User.find({ age: { $gte: 18 } });
// Find with options
const users = await User.find(
{ active: true },
{ limit: 10, skip: 0 }
);Find One Document
const user = await User.findOne({ email: '[email protected]' });Find by ID
const user = await User.findById('user_id');Update Documents
// Update one
await User.updateOne(
{ email: '[email protected]' },
{ $set: { age: 31 } }
);
// Update many
await User.updateMany(
{ active: false },
{ $set: { deleted: true } }
);
// Update instance
const user = await User.findOne({ email: '[email protected]' });
await user.update({ age: 32 });Delete Documents
// Delete one
await User.deleteOne({ email: '[email protected]' });
// Delete many
await User.deleteMany({ active: false });
// Delete instance
const user = await User.findOne({ email: '[email protected]' });
await user.delete();Count Documents
const count = await User.countDocuments({ active: true });
console.log(`Active users: ${count}`);Query Operators
Comparison Operators
$eq- Equal to$gt- Greater than$gte- Greater than or equal$lt- Less than$lte- Less than or equal$ne- Not equal$in- In array$nin- Not in array
Logical Operators
// $in
await User.find({ age: { $in: [25, 30, 35] } });
// $nin
await User.find({ status: { $nin: ['deleted', 'banned'] } });Update Operators
$set- Set field values$unset- Remove fields$inc- Increment numeric field$push- Append to array$pull- Remove from array
await User.updateOne(
{ _id: userId },
{
$set: { name: 'Jane Doe' },
$inc: { age: 1 },
$push: { tags: 'vip' }
}
);Database Operations
Create Database
await asyncdb.createDatabase('myapp');List Databases
const result = await asyncdb.listDatabases();
console.log(result.databases);Create Collection
await asyncdb.createCollection('users');List Collections
const result = await asyncdb.listCollections();
console.log(result.collections);User Management
Create User
await asyncdb.createUser(
'newuser',
'password123',
[{ role: 'readWrite', database: 'myapp' }]
);Available Roles
admin- Full administrative accessreadWrite- CRUD operationsread- Query only (read-only)write- Insert and update only (write-only)
Validation
Documents are validated against the schema before saving:
const userSchema = new asyncdb.Schema({
name: { type: String, required: true },
email: { type: String, required: true }
});
const User = asyncdb.model('User', userSchema);
try {
const user = new User({ name: 'John' }); // Missing email
await user.save();
} catch (error) {
console.error(error.message); // "Validation failed: email is required"
}Error Handling
try {
const user = await User.findById('invalid_id');
if (!user) {
console.log('User not found');
}
} catch (error) {
console.error('Query failed:', error.message);
}Complete Example
const asyncdb = require('asyncdb-mongoose');
async function main() {
try {
// Connect
await asyncdb.connect('async://admin:admin@localhost:32015/myapp');
// Define schema
const productSchema = new asyncdb.Schema({
name: { type: String, required: true },
price: { type: Number, required: true },
stock: { type: Number, default: 0 },
category: String
});
// Create model
const Product = asyncdb.model('Product', productSchema);
// Create product
const laptop = await Product.create({
name: 'Laptop',
price: 999.99,
stock: 10,
category: 'Electronics'
});
console.log('Created:', laptop.toJSON());
// Find products
const electronics = await Product.find({
category: 'Electronics',
price: { $lt: 1000 }
});
console.log('Found:', electronics.length, 'products');
// Update product
await Product.updateOne(
{ _id: laptop._id },
{ $inc: { stock: -1 } }
);
// Disconnect
asyncdb.disconnect();
} catch (error) {
console.error('Error:', error.message);
}
}
main();License
Proprietary Software License - See LICENSE.MD for details.
Support
For issues and questions, please contact OmniAsync by ZF Corporation (Private) Limited.
