MongoDB with Mongoose (Node.js)
Uses Mongoose 9.11. The code is an ordinary application for the original database; nothing in it knows about MachNoSQL.
The only change
Section titled “The only change”mongodb://app:secret@mongo.example.com:27017/shop?authSource=adminmongodb://app:secret@machnosql.example.com:27017/shop?authSource=adminThe address comes from the environment variable MONGODB_URI, so switching to MachNoSQL changes configuration only.
export MONGODB_URI='mongodb://app:secret@machnosql.example.com:27017/shop?authSource=admin'npm installnpm startSource
Section titled “Source”The program as it is kept and tested in the Mach Database NoSQL repository; highlighted lines read the connection setting.
// Orders example with Mongoose models, unchanged on MachNoSQL.import mongoose from "mongoose";
const orderSchema = new mongoose.Schema({ customer: { type: String, required: true, index: true }, item: { type: String, required: true }, qty: { type: Number, min: 1 }, price: Number,});const Order = mongoose.model("Order", orderSchema);
await mongoose.connect(process.env.MONGODB_URI);
await Order.deleteMany({});await Order.create([ { customer: "ada", item: "keyboard", qty: 1, price: 49.0 }, { customer: "ada", item: "mouse", qty: 2, price: 19.5 }, { customer: "linus", item: "monitor", qty: 1, price: 199.0 },]);
const mouse = await Order.findOne({ item: "mouse" }).lean();console.log(mouse);await Order.updateOne({ item: "mouse" }, { $inc: { qty: 1 } });
const revenue = await Order.aggregate([ { $group: { _id: "$customer", revenue: { $sum: { $multiply: ["$qty", "$price"] } } } }, { $sort: { revenue: -1 } },]);console.log(revenue);
await mongoose.disconnect();{ "name": "machnosql-example-mongoose", "private": true, "type": "module", "scripts": { "start": "node app.js" }, "dependencies": { "mongoose": "^9.11.4" }}