@dataql/mongoose-adapter
v1.4.0
Published
Mongoose adapter for DataQL with zero API changes (simplified core functionality)
Downloads
15
Maintainers
Readme
@dataql/mongoose-adapter (Simplified Core Functionality)
Migrate from Mongoose to DataQL with zero API changes for core functionality. This adapter provides essential Mongoose-compatible APIs that run on DataQL with automatic scaling, caching, and offline support.
Note: This is a simplified version focusing on the most commonly used Mongoose features to ensure stability and compatibility.
Installation
npm install @dataql/core @dataql/mongoose-adapterSupported Features
✅ Core CRUD Operations
Model.create(),Model.find(),Model.findOne(),Model.findById()Model.updateOne(),Model.updateMany(),Model.deleteOne(),Model.deleteMany()Model.findOneAndUpdate(),Model.findOneAndDelete(),Model.countDocuments()
✅ Schema Definition
- Basic schema types:
String,Number,Boolean,Date,Array - Schema options:
required,default,enum,ref - Timestamps support with
{ timestamps: true }
✅ Query Interface
- Promise-based queries with
.exec(),.then(),.catch() - Basic filtering and operations
⚠️ Simplified/Not Included
- Complex query builders (
.where(),.gt(),.lt(), etc.) - Population and advanced relationships
- Middleware (
.pre(),.post()hooks) - Virtual properties
- Complex validation
- Aggregation pipelines
Quick Start
import mongoose, { Schema } from "@dataql/mongoose-adapter";
// Connect with DataQL configuration
await mongoose.connect("mongodb://localhost:27017/myapp", {
appToken: "your-app-token", // Required for DataQL authentication
env: "prod", // Environment: 'dev' or 'prod'
dbName: "myapp_client1", // Database isolation per client
});
// Define schemas (simplified syntax)
const userSchema = new Schema(
{
name: { type: String, required: true },
email: { type: String, required: true },
age: Number,
role: { type: String, enum: ["admin", "user", "guest"] },
profile: {
bio: String,
avatar: String,
},
tags: [String],
},
{ timestamps: true }
);
// Create model
const User = mongoose.model("User", userSchema);
// Use familiar Mongoose API
const user = await User.create({
name: "John Doe",
email: "[email protected]",
age: 30,
role: "user",
profile: {
bio: "Software developer",
avatar: "avatar.jpg",
},
tags: ["javascript", "node.js"],
});
// Query operations
const users = await User.find({ role: "user" });
const john = await User.findById(user._id);
const updated = await User.findOneAndUpdate(
{ email: "[email protected]" },
{ age: 31 },
{ new: true }
);
// Bulk operations
await User.updateMany({ role: "user" }, { $set: { active: true } });
await User.deleteMany({ active: false });
// Count and distinct
const userCount = await User.countDocuments({ role: "user" });
const uniqueRoles = await User.distinct("role");Schema Definition
// Basic schema types
const productSchema = new Schema({
name: String,
price: Number,
inStock: Boolean,
createdAt: Date,
tags: [String],
// Object types
dimensions: {
width: Number,
height: Number,
depth: Number,
},
// Schema options
category: {
type: String,
enum: ["electronics", "books", "clothing"],
required: true,
},
description: {
type: String,
default: "No description available",
},
// References (basic support)
sellerId: { type: String, ref: "User" },
});Migration from Mongoose
Most common Mongoose code will work without changes:
// Before (Mongoose)
import mongoose from "mongoose";
await mongoose.connect("mongodb://localhost:27017/myapp");
// After (DataQL)
import mongoose from "@dataql/mongoose-adapter";
await mongoose.connect("mongodb://localhost:27017/myapp", {
appToken: "your-app-token",
dbName: "myapp_client1",
});
// Same model definition and usage
const User = mongoose.model("User", userSchema);
const users = await User.find({ active: true });Configuration Options
interface MongooseDataQLOptions {
// Required for DataQL infrastructure routing
appToken?: string;
// Database name for client isolation
dbName?: string;
// Environment routing (dev/prod)
env?: "dev" | "prod";
// Development prefix
devPrefix?: string;
// Optional custom connection
customConnection?: any;
// Mongoose compatibility options
useNewUrlParser?: boolean;
useUnifiedTopology?: boolean;
bufferCommands?: boolean;
autoIndex?: boolean;
autoCreate?: boolean;
}Error Handling
import { ValidationError, CastError } from "@dataql/mongoose-adapter";
try {
await User.create({ name: "Invalid", age: "not-a-number" });
} catch (error) {
if (error instanceof ValidationError) {
console.log("Validation failed:", error.errors);
} else if (error instanceof CastError) {
console.log("Cast error:", error.path, error.value);
}
}DataQL Benefits
By using DataQL instead of direct MongoDB connections:
- Automatic Scaling: Resources scale based on demand
- Global Performance: Faster response times worldwide
- Offline Support: Applications work without connectivity
- Real-time Sync: Data syncs when connectivity returns
- Data Isolation: Each client gets dedicated database
- Simplified Setup: No database setup or management needed
Limitations
This simplified adapter focuses on core functionality to ensure reliability:
- No complex query builders: Use basic filter objects instead
- No population: Handle relationships manually
- No middleware: Use application-level logic instead
- No virtuals: Compute derived values in application code
- No aggregation: Use find operations and JavaScript processing
For applications requiring advanced Mongoose features, consider using individual DataQL operations or the full DataQL SDK.
Need More Features?
For advanced use cases, consider:
- @dataql/core: Full DataQL SDK with advanced querying
- @dataql/mongodb-adapter: Full MongoDB driver compatibility
- Custom implementation: Use DataQL core for specific requirements
Examples
See examples/basic-usage.ts for complete usage examples with various schema types and operations.
