└── README.md /README.md: -------------------------------------------------------------------------------- 1 | # Mongoose Cheat Sheet 2 | Mongoose can refer to a JavaScript library used with MongoDB, providing an object data modeling (ODM) layer for Node.js applications. It simplifies interactions with MongoDB by offering a schema-based approach and additional features for managing data. 3 | 4 | ## Follow these steps to connect your MongoDB database with Mongoose 5 | 6 | ### 1. Basic Express JS steps: 7 | ```JS 8 | const express = require("express"); 9 | const app = express(); 10 | const port = process.env.PORT || 5000; 11 | 12 | // MIDDLEWARE 13 | app.use( 14 | cors({ 15 | origin: [ 16 | "http://localhost:5173", 17 | "https://sabbir-mohammad-sami.web.app/" 18 | "https://sabbir-mohammad-sami.web.app/" 19 | ], 20 | }) 21 | ); 22 | app.use(express.json()); 23 | 24 | //APPLICATION ROUTE 25 | app.get("/", (req, res) => { 26 | res.send("Industry Running..."); 27 | }); 28 | 29 | const main = async () => { 30 | app.listen(port, () => { 31 | console.log("Industry running on port: ", { port }); 32 | }); 33 | }; 34 | main() 35 | 36 | ``` 37 | ### 2. connect database using mongoose 38 | ```JS 39 | const express = require("express"); 40 | const app = express(); 41 | const port = process.env.PORT || 5000; 42 | const { default: mongoose } = require("mongoose"); 43 | 44 | // MIDDLEWARE 45 | app.use( 46 | cors({ 47 | origin: [ 48 | "http://localhost:5173", 49 | "https://sami-industry.web.app/", 50 | "https://sami-industry.firebaseapp.com", 51 | ], 52 | }) 53 | ); 54 | app.use(express.json()); 55 | 56 | // ROUTE 57 | // 58 | 59 | // APPLICATION ROUTE 60 | app.get("/", (req, res) => { 61 | res.send("Industry Running..."); 62 | }); 63 | 64 | // CONNECT WITH DB 65 | const connectDB = async () => { 66 | try { 67 | const url = ; 68 | await mongoose.connect(url); 69 | console.log("Database connect successfully"); 70 | } catch (error) { 71 | console.log("connection fail", error); 72 | } 73 | }; 74 | 75 | const main = async () => { 76 | await connectDB() 77 | app.listen(port, () => { 78 | console.log("Industry running on port: ", { port }); 79 | }); 80 | }; 81 | main() 82 | 83 | ``` 84 | 85 | ### Connect Mongoose with the existing database 86 | ```JS 87 | const connectDB = async () => { 88 | try { 89 | const url = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@clusterName.5nhfk.mongodb.net/?retryWrites=true&w=majority`; 90 | await mongoose 91 | .connect(url, { 92 | dbName: "", 93 | }) 94 | .then(() => { 95 | console.log("Database connect successfully"); 96 | }) 97 | .catch((err) => { 98 | console.log("connection fail", error); 99 | }); 100 | } catch (error) { 101 | console.log("connection fail", error); 102 | } 103 | }; 104 | 105 | ``` 106 | 107 | ### 3. Now if you have a gallery section where users can add photo with captions and you want to save this data in your database with imageUrl, caption, uploadDate, uploadedBy. Then you need to create a Schema first. 108 | #### `Now the question is what is Schema in Mongoose?` 109 | In Mongoose, a schema is a blueprint that defines the structure of documents within a collection in a MongoDB database. You can check and validate what the user is trying to post if it is not what you need then you can throw an error message. 110 | 111 | ### - Create a Schema for your gallery section post 112 | 113 | ```JS 114 | // Define the Mongoose schema 115 | const imageSchema = new mongoose.Schema({ 116 | imageUrl: { 117 | type: String, 118 | required: true, // if you set (required: true,) then if the user doesn't provide this URL it will not 119 | // save data. But if it's not required then you can just remove it. 120 | }, 121 | caption: { 122 | type: String, 123 | maxLength: 150, 124 | }, 125 | uploadDate: { 126 | type: Date, 127 | default: Date.now, 128 | }, 129 | uploadedBy: { 130 | type: String, 131 | required: true, 132 | }, 133 | }); 134 | 135 | // Create a Mongoose model based on the schema. This model first parameter defines what's going to be your 136 | // database collection name. But remember if you set your database name image then it saves the database 137 | // collection name as images which means it always adds s to your provided model name. 138 | 139 | const Image = mongoose.model('Image', imageSchema); 140 | 141 | ``` 142 | #### - Post image 143 | ```JS 144 | app.post("/images", async (req, res) => { 145 | try { 146 | const newImage = new Image(req.body); 147 | const result = await newImage.save(); 148 | res.send(result) 149 | } catch (error) { 150 | console.error("Error adding image to the gallery:", error.message); 151 | } 152 | }); 153 | ``` 154 | 155 | #### - Get All images 156 | ```JS 157 | app.get("/images", async (req, res) => { 158 | try { 159 | const result = await Image.find({}); 160 | res.send(result); 161 | } catch (error) { 162 | console.error("Error getting image to the gallery:", error.message); 163 | } 164 | }); 165 | ``` 166 | #### - Update image 167 | ```JS 168 | app.put("/images/:id", async (req, res) => { 169 | try { 170 | const updatedImage = req.body.image; 171 | const result = await Image.updateOne( 172 | { _id: req.params.id }, 173 | { 174 | $set: { imageUrl: updatedImage }, 175 | } 176 | ); 177 | if (result.nModified > 0) { 178 | return res 179 | .status(200) 180 | .json({ message: "imageUrl updated successfully" }); 181 | } else { 182 | return res 183 | .status(404) 184 | .json({ error: "imageUrl update fail" }); 185 | } 186 | } catch (error) { 187 | console.log(error); 188 | } 189 | }); 190 | ``` 191 | #### - Delete image 192 | ```JS 193 | app.delete("/images/:id", async (req, res) => { 194 | try { 195 | const result = await Image.deleteOne({ _id: req.params.id }); 196 | res.send(result); 197 | } catch (error) { 198 | console.log(error); 199 | } 200 | }); 201 | ``` 202 | 203 | #### You can put everything part by part in different folders. But don't forget to export it. Here is an example if you put schema in a different folder: 204 | ```JS 205 | const mongoose = require('mongoose'); 206 | 207 | const imageSchema = new mongoose.Schema({ 208 | imageUrl: { 209 | type: String, 210 | required: true, 211 | }, 212 | caption: { 213 | type: String, 214 | maxLength: 150, 215 | }, 216 | uploadDate: { 217 | type: Date, 218 | default: Date.now, 219 | }, 220 | uploadedBy: { 221 | type: String, 222 | required: true, 223 | }, 224 | }); 225 | 226 | const Image = mongoose.model('Image', imageSchema); 227 | 228 | module.exports = Image; 229 | ``` 230 | 231 | ### Validation and Sanitization: 232 | 233 | - #### Validation for String Length: 234 | ```JS 235 | caption: { 236 | type: String, 237 | maxLength: 150, 238 | minLength: 5, 239 | }, 240 | 241 | ``` 242 | - #### Custom Validation with a Regular Expression: 243 | ```JS 244 | 245 | imageUrl: { 246 | type: String, 247 | required: true, 248 | validate: { 249 | validator: function (value) { 250 | // Validate that the URL follows a specific pattern 251 | return /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/.test(value); 252 | }, 253 | message: "Invalid imageUrl format", 254 | }, 255 | }, 256 | 257 | ``` 258 | - #### Validation for Date: 259 | ```JS 260 | 261 | uploadDate: { 262 | type: Date, 263 | default: Date.now, 264 | validate: { 265 | validator: function (value) { 266 | // Validate that the date is not in the future 267 | return value <= Date.now(); 268 | }, 269 | message: "Invalid uploadDate, must not be in the future", 270 | }, 271 | }, 272 | 273 | ``` 274 | 275 | #### ` ⚠ This is a single-file example for absolute beginners. If you find any bug or any kind of problem don't forget to inform me. If you find it truly helpful don't forget to give it a star ⭐` 276 | 277 | ## Some additional information: 278 | #### Insert 279 | 280 | | Command | Description | 281 | |---------|-------------| 282 | | `insertOne` | Create a new document inside the specified collection | 283 | | `db.users.insertOne({ name: “Sami” })` | Add a new document with the name of Sami into the users collection | 284 | | `insertMany` | Create multi new documents inside a specific collection | 285 | | `db.users.insertMany([{ age: 26 }, { age: 20 }])` | Add two new documents with the age of 26 and 20 into the users collection | 286 | | ___________________ | _____________________________________________________________________________________________________________________| 287 | 288 | #### Read 289 | 290 | | Command | Description | 291 | |---------|-------------| 292 | | `find` | Get all documents | 293 | | `db.users.find()` | Get all users | 294 | | `find()` | Find all documents that match the filter object | 295 | | `db.users.find({ name: “Sami” })` | Get all users with the name Sami | 296 | | `db.users.find({ “address.street”: “123 Main St” })` | Get all users whose address field has a street field with the value 123 Main St | 297 | | `find(, )` | Find all documents that match the filter object but only return the field specified in the select object | 298 | | `db.users.find({ name: “Sami” }, { name: 1, age: 1 })` | Get all users with the name Sami but only return their name, age, and _id | 299 | | `db.users.find({}, { age: 0 })` | Get all users and return all columns except for age | 300 | | `findOne` | The same as find, but only return the first document that matches the filter object | 301 | | `db.users.findOne({ name: “Sami” })` | Get the first user with the name Sami | 302 | | `countDocuments` | Return the count of the documents that match the filter object passed to it | 303 | | `db.users.countDocuments({ name: “Sami” })` | Get the number of users with the name Sami | 304 | 305 | #### Update 306 | 307 | | Command | Description | 308 | |---------|-------------| 309 | | `updateOne` | Update the first document that matches the filter object with the data passed into the second parameter which is the update object | 310 | | `db.users.updateOne({ age: 20 }, { $set: { age: 21 } })` | Update the first user with an age of 20 to the age of 21 | 311 | | `updateMany` | Update all documents that match the filter object with the data passed into the second parameter which is the update object | 312 | | `db.users.updateMany({ age: 12 }, { $inc: { age: 3 } })` | Update all users with an age of 12 by adding 3 to their age | 313 | | `replaceOne` | Replace the first document that matches the filter object with the exact object passed as the second parameter. This will completely overwrite the entire object and not just update individual fields | 314 | | `db.users.replaceOne({ age: 12 }, { age: 13 })` | Replace the first user with an age of 12 with an object that has the age of 13 as its only field | 315 | 316 | #### Delete 317 | 318 | | Command | Description | 319 | |---------|-------------| 320 | | `deleteOne` | Delete the first document that matches the filter object | 321 | | `db.users.deleteOne({ age: 20 })` | Delete the first user with an age of 20 | 322 | | `deleteMany` | Delete all documents that match the filter object | 323 | | `db.users.deleteMany({ age: 12 })` | Delete all users with an age of 12 | 324 | | ___________________ | _____________________________________________________________________________________________________________________| 325 | 326 | #### Complex Filter Object 327 | 328 | | Operator | Description | 329 | |----------|-------------| 330 | | `$eq` | Check for equality | 331 | | `$ne` | Check for not equal | 332 | | `$gt` / `$gte` | Check for greater than and greater than or equal to | 333 | | `$lt` / `$lte` | Check for less than and less than or equal to | 334 | | `$in` | Check if a value is one of many values | 335 | | `$nin` | Check if a value is none of many values | 336 | | `$and` | Check that multiple conditions are all true | 337 | | `$or` | Check that one of multiple conditions is true | 338 | | `$not` | Negate the filter inside of `$not` | 339 | | `$exists` | Check if a field exists | 340 | | `$expr` | Do comparisons between different fields | 341 | | ___________________ | _____________________________________________________________________________________________________________________________| 342 | 343 | #### Complex Update Object 344 | 345 | | Operator | Description | 346 | |----------|-------------| 347 | | `$set` | Update only the fields passed to `$set`. This will not affect any fields not passed to `$set` | 348 | | `$inc` | Increment the value of the field by the amount given | 349 | | `$rename` | Rename a field | 350 | | `$unset` | Remove a field | 351 | | `$push` | Add a value to an array field | 352 | | `$pull` | Remove a value from an array field | 353 | | ___________________ | _____________________________________________________________________________________________________________________________| 354 | 355 | #### Read Modifiers 356 | 357 | | Modifier | Description | 358 | |----------|-------------| 359 | | `sort` | Sort the results of a find by the given fields | 360 | | `limit` | Only return a set number of documents | 361 | | `skip` | Skip a set number of documents from the beginning | 362 | | ___________________ | _____________________________________________________________________________________________________________________________| 363 | 364 | #### `If you find any kind of error please don't hesitate to reach me.😊 Or if you find it truly helpful don't forget to give it a star ⭐` 365 |

366 | Contact: 367 | Portfolio → Discord → 368 |

369 | 370 | --------------------------------------------------------------------------------