Use Mongoose with DaloyJS
Mongoose is the default ODM choice for MongoDB teams who want schemas, model middleware, casting, validation, and transactions through sessions. It fits naturally into DaloyJS when you register the connection once and expose a small model surface on state.
- 01Installpnpm add mongoose
- 02Schema & modelnew Schema · model('User')
- 03Pluginconnect · decorate('db') · onClose
- 04Augment stateinterface AppState { db }
- 05Use in routesstate.db.User.findById()
1. Install
2. Define a schema and model
3. Create a Mongoose plugin
4. Augment app state types
5. Use it in routes
Sessions and transactions
Use MongoDB sessions for multi-document transactions. Start the session inside the handler and thread it through every model call in the unit of work.
- 01requestHandlerSessionStart a sessionstartSession()
- 02requestHandlerModelsRun every write inside withTransactionUser.create([...], { session })
- 03responseSessionHandlerCommit on success, roll back on throw
- 04noteHandlerSessionAlways end the session in finallyendSession()
Validation and errors
Keep transport validation in Zod and let Mongoose own document-level validation. Translate duplicate key or cast failures into DaloyJS errors so they serialize as problem+json.
Runtime constraints
Mongoose is a Node.js-first ODM because it depends on the MongoDB Node driver. For SQL databases or edge runtimes, stay in the ORM section instead.
Compare with Ottoman for Couchbase, Prisma for SQL, or return to the ODM overview.