bởi Rowan E.

Mongoose is a MongoDB object modeling library for Node.js and Deno, providing schema-based data modeling with built-in validation, middleware, query building, and plugin support.
This block provides the full Mongoose ODM core library (lib/), an object modeling layer that maps MongoDB documents to JavaScript objects via schemas, models, and validators. It is aimed at Node.js/TypeScript backend developers who need structured, schema-enforced access to MongoDB without writing raw driver queries.
aggregate.js - Chainable MongoDB aggregation pipeline buildercast.js - Top-level value casting dispatchercast/ - Per-type cast functions (bigint, boolean, date, decimal128, double, int32, number, objectid, string, uuid)collection.js - Abstract collection base classconnection.js - Connection lifecycle management (open, close, events)connectionState.js - Enum of connection state codesconstants.js - Internal shared constant valuescursor/ - Streaming cursor types: QueryCursor, AggregationCursor, ChangeStreamdocument.js - Base Document class (get/set, validate, save)driver.js - Driver registration singletondrivers/ - Node.js MongoDB native driver adapter (collection, connection, bulk write)error/ - All Mongoose error classes (ValidationError, CastError, etc.)helpers/ - Internal utilities (discriminator wiring, document helpers, cursor helpers)index.js - Package entry point; wires driver and exports the mongoose instanceinternal.js - Internal symbols used across the codebasemodel.js - Model class (CRUD, indexing, population, bulk ops)modifiedPathsSnapshot.js - Snapshot utility for tracking dirty pathsmongoose.js - The Mongoose class constructor; creates isolated instancesoptions.js - Global Mongoose option defaultsoptions/ - Per-option validation helpersplugins/ - Built-in plugins: saveSubdocs, sharding, trackTransactionquery.js - Chainable query builder (find, update, delete, etc.)queryHelpers.js - Utilities consumed by query.jsschema.js - Schema definition classKhởi chạy sandbox cách ly và chạy phía máy chủ — không cần cài đặt cục bộ.
Tetrees AI Review cho phiên bản này
This JavaScript cli / script completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Quy trình avcp-2026-08-04.1 · SHA-256 9c443ccede345bf3…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Đã đánh giá 4 thg 8, 2026
Đưa sản phẩm này thẳng vào AI IDE, trình tạo web hoặc cloud IDE của bạn.
Kết nối Tetrees với AI IDE tương thích để liệt kê sản phẩm bạn sở hữu và nhận ZIP đã xác minh mà không cấp quyền tải lên của người bán.
Chưa có đánh giá.
Sign in to join the discussion
Loading discussion…
schema/ - Schema type implementations (Array, Boolean, Date, Number, String, ObjectId, Map, Mixed, UUID, etc.)schemaType.js - Base SchemaType class all schema types extendstateMachine.js - Generic finite state machine used by connections and documentstypes/ - Runtime types exposed on the mongoose object (DocumentArray, Buffer, etc.)utils.js - General-purpose internal utility functionsvalidOptions.js - Allowlist of valid schema/model optionsvirtualType.js - Virtual path definition (getter/setter without DB persistence)npm install user@example.com
npm install kareem mpath mquery ms sift mongodb
No native build steps are required. mongoose targets Node.js >= 16. No pod install, Android linking, or Expo prebuild is needed.
source/ directory into your project, e.g. src/vendor/mongoose-lib/.// tsconfig.json
{
"compilerOptions": {
"paths": {
"mongoose-core/*": ["src/vendor/mongoose-lib/*"]
}
}
}
import mongoose from 'mongoose'; // resolves to source/index.js via npm
MONGODB_URI=mongodb://127.0.0.1:27017/mydb
mongoose.connect() once at application startup (before any model operations).import mongoose from 'mongoose';
// or from source directly:
const mongoose = require('./source/index');
The default export is a singleton Mongoose instance. Use it to call connect, define schemas/models, and access the full error hierarchy. It exposes .Mongoose for creating isolated instances and .mongo for the raw MongoDB driver.
import { Schema } from 'mongoose';
const schema = new Schema(
{ name: String; age: Number },
{ timestamps: true }
);
Defines the shape, defaults, validators, indexes, and virtuals for a collection. Pass to mongoose.model(). Available schema types: String, Number, Boolean, Date, Buffer, Mixed, ObjectId, Array, Map, Decimal128, UUID, BigInt, Double, Int32.
import mongoose from 'mongoose';
const {
ValidationError,
ValidatorError,
CastError,
DocumentNotFoundError,
VersionError,
} = mongoose.Error;
The error namespace mirrors source/error/index.js. Use it in catch blocks to distinguish Mongoose-specific errors (e.g. err instanceof mongoose.Error.CastError) from driver-level or network errors.
import mongoose from 'mongoose';
const conn = mongoose.createConnection('mongodb://127.0.0.1:27017/mydb');
conn.on('connected', () => console.log('ready'));
conn.on('error', (err) => console.error(err));
createConnection returns a Connection instance (source/connection.js). Use it when you need multiple databases in the same process. Each connection manages its own model registry.
A typical REST API route handler that creates a new user document and reads it back.
import mongoose, { Schema, Document } from 'mongoose';
interface IUser extends Document {
name: string;
email: string;
createdAt: Date;
}
const userSchema = new Schema<IUser>(
{
name: { type: String, required: true, trim: true },
email: { type: String, required: true, unique: true, lowercase: true },
},
{ timestamps: true }
);
const User = mongoose.model<IUser>('User', userSchema);
async function run() {
await mongoose.connect(process.env.MONGODB_URI!);
const user = await User.create({ name: 'Alice', email: 'alice@example.com' });
console.log(user._id);
const found = await User.findOne({ email: 'alice@example.com' }).lean();
console.log(found?.name);
await mongoose.disconnect();
}
run();
Demonstrates the mongoose.Error.ValidationError class exported from source/error/index.js.
import mongoose, { Schema } from 'mongoose';
const productSchema = new Schema({
title: { type: String, required: true },
price: { type: Number, min: [0, 'Price must be non-negative'] },
category: { type: String, enum: ['book', 'electronics', 'clothing'] },
});
const Product = mongoose.model('Product', productSchema);
async function createProduct(data: object) {
await mongoose.connect(process.env.MONGODB_URI!);
try {
const doc = new Product(data);
await doc.validate(); // throws ValidationError before hitting DB
await doc.save();
return doc;
} catch (err) {
if (err instanceof mongoose.Error.ValidationError) {
// err.errors is a map of path -> ValidatorError
for (const [path, ve] of Object.entries(err.errors)) {
console.error(`${path}: ${ve.message}`);
}
}
throw err;
}
}
createProduct({ title: '', price: -5, category: 'unknown' });
Uses createConnection from source/connection.js to connect two databases independently.
import mongoose from 'mongoose';
const connA = mongoose.createConnection('mongodb://127.0.0.1:27017/db_a');
const connB = mongoose.createConnection('mongodb://127.0.0.1:27017/db_b');
const LogSchema = new mongoose.Schema({ message: String, level: String });
const LogA = connA.model('Log', LogSchema);
const LogB = connB.model('Log', LogSchema);
async function writeLog(db: 'a' | 'b', message: string) {
const Model = db === 'a' ? LogA : LogB;
await Model.create({ message, level: 'info' });
}
(async () => {
await Promise.all([connA.asPromise(), connB.asPromise()]);
await writeLog('a', 'hello from db_a');
await writeLog('b', 'hello from db_b');
await connA.close();
await connB.close();
})();
index.js - Wires the node-mongodb-native driver, calls setDriver, attaches .mongo (raw driver), and re-exports the mongoose singleton.mongoose.js - Defines the Mongoose class; index.js uses a singleton of it as the default export.schema.js - Schema constructor; parses path definitions and stores type trees, validators, indexes, and hooks.schema/ - One file per schema type; each extends schemaType.js and implements cast(), castForQuery(), and validation.model.js - Model class; static methods (find, create, updateMany, aggregate, bulkWrite) and instance methods (save, remove).document.js - Base Document; tracks modified paths, runs validation, serializes to plain objects.query.js - Chainable query builder; methods like .select(), .populate(), .sort(), .lean(), .exec().connection.js - Manages a single MongoDB connection, emits lifecycle events, owns its model registry.aggregate.js - Fluent aggregation pipeline builder returned by Model.aggregate().error/ - Full error hierarchy: MongooseError → ValidationError, CastError, DocumentNotFoundError, VersionError, etc.cast/ - Stateless functions that coerce raw values to their schema types (used internally by query and document paths).cursor/ - QueryCursor (.cursor()), AggregationCursor (.cursor() on aggregate), and ChangeStream wrappers.drivers/node-mongodb-native/ - Thin adapter classes (Collection, Connection) that delegate to the official mongodb driver.plugins/ - Three built-in plugins applied globally: saveSubdocs, sharding, trackTransaction.helpers/ - Private helpers for discriminators, document internals, and cursor operations; not part of public API.schemaType.js - Abstract base for all schema types; defines the cast, validate, default, and index contract.virtualType.js - Represents a virtual path with .get() and .set() callbacks (no DB column).stateMachine.js - Lightweight finite state machine backing connection and document state transitions.utils.js - Internal helpers (deep clone, merge, type checks); not a public API.mongoose.model() before connect() resolves - Model definition is fine before connecting, but operations (save, find) queue and may time out; always await mongoose.connect() at startup.OverwriteModelError - Use mongoose.models.User || mongoose.model('User', schema) to guard hot-reload environments (Next.js, ts-node-dev)._id with string ObjectId values - Mongoose casts automatically; if you bypass with .lean() + raw filter, pass new mongoose.Types.ObjectId(id) explicitly.Document generic and lean() returning {} type - Use Model.findOne().lean<IUser>() or define your model as Model<IUser> to preserve types through lean queries.mongoose@9 drops callback support - All async methods return Promises only; remove all callback-style calls (e.g. Model.find({}, cb)) or the callback is silently ignored.new mongoose.Mongoose() for isolation, remember to call setDriver on the new instance or you will get a "driver not set" error at runtime.I have placed the Mongoose ODM core source (mongoose@9.5.0) at `src/vendor/mongoose-lib/`
and a USAGE.md integration guide alongside it.
Please help me integrate this library into my Node.js/TypeScript project step by step:
1. Read USAGE.md and `src/vendor/mongoose-lib/index.js` to understand the entry point and exports.
2. Install all required dependencies listed in USAGE.md (kareem, mongodb, mpath, mquery, ms, sift).
3. Create a `src/db.ts` file that calls `mongoose.connect()` using the MONGODB_URI environment variable
and exports the mongoose instance.
4. Define a typed Mongoose schema and model for [DESCRIBE YOUR ENTITY] in `src/models/[entity].ts`,
using the Schema types from `src/vendor/mongoose-lib/schema/index.js`.
5. Add CRUD service functions (create, findById, update, delete) in `src/services/[entity]Service.ts`.
6. Wire up error handling using `mongoose.Error.ValidationError` and `mongoose.Error.CastError`
as shown in USAGE.md.
7. Verify TypeScript types compile without errors.
Constraints: use user@example.com API only (no callbacks, Promises only). Reference real exports
from USAGE.md. Do not invent methods not present in the source.
Mongoose is released under the MIT License. See source/LICENSE if present in this block, or refer to the official repository. Upstream package: mongoose on npm.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
Hướng dẫn cài đặt đầy đủ và prompt tích hợp sẽ mở khóa sau khi mua.
Automation, Utilities & Developer Tools
Miễn phí