Move a Mongoose application to TeselaDB
TeselaDB
TeselaDB team
20 minBeginner
Connect your Mongoose models to TeselaDB, check that they save and read the same and review what changes.
Mongoose talks to the database through the official MongoDB driver for Node.js, so your schemas, your validations and your queries stay the same. What changes is the connection string and, in some cases, a behaviour from the list of differences from MongoDB.
What you will build
A Mongoose model with its schema that saves and reads orders in TeselaDB. With it you check that your application works against the cluster before you move all of it.
Requirements
- Node.js 18 or later and Mongoose 8 or later.
- A TeselaDB cluster with your data already migrated, if you have it in MongoDB (Migrate from MongoDB).
- The connection string with TLS in the
TESELADB_URIenvironment variable.
1. Change the connection string
If your application already reads the string from an environment variable, give it the TeselaDB one:
export TESELADB_URI="mongodb://shop-api:<password>@node-01:27017,node-02:27017/shop?tls=true&tlsCAFile=./ca.pem"2. Try a model
Save this as order.mjs, with a schema that validates its fields and stamps the creation and update times:
import mongoose from "mongoose";
const Order = mongoose.model(
"Order",
new mongoose.Schema(
{ customer: { type: String, required: true }, total: { type: Number, min: 0 } },
{ timestamps: true },
),
);
await mongoose.connect(process.env.TESELADB_URI);
await Order.create({ customer: "Ana", total: 30 });
console.log(await Order.countDocuments({ customer: "Ana" }));
await mongoose.disconnect();Try it
Run node order.mjs. The program connects with Mongoose using the string in TESELADB_URI, creates an order for Ana
with a total of 30 and then counts her orders, so against an empty database it prints the number 1:
1Then run your application's tests against TeselaDB. If one fails, check first whether it depends on the order of a
find without sort, which in TeselaDB returns the documents in the order of their key.
Clean up
db.getSiblingDB("shop").orders.deleteMany({ customer: "Ana" });Run it in mongosh to delete the test orders, all of them with Ana as the customer.
Next steps
- ODMs and ORMs, with Spring Data MongoDB and Beanie.
- Differences with MongoDB, in case your application depends on one.