What is ODM?
ODM = Object Data Modeling
- Work with MongoDB using JavaScript objects
- Instead of writing raw MongoDB queries
Create Methods:
Create and save document
await User.create({ name, email });new Model() + save()
const user = new User({ name, email });
await user.save();Read Query Method:
await User.find(); // Get All Document
await User.findOne({ email }); // Get One Document
await User.findByIdAndUpdate(id, { name: "New" }, { new: true }); // Find By ID and Update
await User.findByIdAndDelete(id); // Find ny id and delete
await User.findOneAndUpdate(
{ email },
{ name: "Updated" },
{ new: true }
);
await User.findOneAndDelete({ email });Update Method:
await User.updateOne({ email }, { name: "New Name" });
await User.updateMany({ role: "user" }, { status: "active" });
await User.replaceOne({ email }, { name: "Only This Data" });Delete Method:
await User.deleteOne({ email });
await User.deleteMany({ status: "inactive" });Count Check Menthod:
const count = await User.countDocuments();
const exists = await User.exists({ email });Advanced Query Methos:
await User.find().select("name email");
await User.find().limit(10);
await User.find().skip(10).limit(10);
await User.find().sort({ createdAt: -1 });
await User.find().populate("profileId"); // JoinsAggreation:
await User.aggregate([
{ $match: { status: "active" } },
{ $group: { _id: "$role", total: { $sum: 1 } } }
]);Schema Method:
// Instance Method
userSchema.methods.sayHello = function () {
return "Hello";
};
// Static Method
userSchema.statics.findByEmail = function (email) {
return this.findOne({ email });
};Middleware Hooks:
Before:
userSchema.pre("save", function (next) {
console.log("Before Save");
next();
});After
userSchema.post("save", function (doc) {
console.log("Saved:", doc);
});