Last active
January 21, 2021 13:29
-
-
Save sahilrajput03/3e393933c0d376208dbfe600e5d43950 to your computer and use it in GitHub Desktop.
mongoose general usage methods #mongoose #mongodb #database #mongo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Playground: https://mongoplayground.net/ | |
| // Documentation: https://mongoosejs.com/docs/ | |
| // Cheatsheet1: https://kb.objectrocket.com/mongo-db/the-mongoose-cheat-sheet-225 | |
| // Cheatsheet2: https://github.com/azat-co/cheatsheets/blob/master/mongodb-mongoose/readme.md | |
| const {Schema, model, connect} = require("mongoose"); | |
| let log = console.log; | |
| function connectMongoDb() { | |
| log("Connecting to database☻..."); | |
| connect("mongodb://localhost/admin", { | |
| useNewUrlParser: true, | |
| useUnifiedTopology: true, | |
| useFindAndModify: false, | |
| useCreateIndex: true, | |
| }); | |
| // .then(() => { | |
| // log("connection successful☺"); | |
| // }) | |
| // .catch((error) => { | |
| // log("error connection to MongoDB:", error.message); | |
| // }); | |
| } | |
| const noteSchema = new Schema({ | |
| name: { | |
| type: String, | |
| required: true, | |
| unique: true, | |
| minlength: 4, | |
| }, | |
| born: { | |
| type: Number, | |
| }, | |
| }); | |
| const userSchema = new Schema({ | |
| username: { | |
| type: String, | |
| required: false, | |
| unique: false, | |
| minlength: 2, | |
| }, | |
| name: { | |
| type: String, | |
| }, | |
| friends: { [{type: Schema.Types.ObjectId, ref: GADGET_COLLECTION_NAME}] } // This tells joining to another collection name. | |
| }); | |
| const userModel = model("User", userSchema); | |
| const noteModel = model("Note", noteSchema); // ? Not used in below code though. | |
| connectMongoDb(); | |
| async function main() { | |
| log("$log1-", await userModel.collection.countDocuments()); | |
| log("$log2-", await userModel.find({})); // This returns an array of document(objects).Yikes!!! | |
| log("$log3-", await userModel.find({phone: {number: 235234}})); | |
| log("$log4-", await userModel.findOne({name: "sahil"})); | |
| log("$log5-", await userModel.findById("asfasf92h9sh9sf").populate("friends"));// You are supposed to pass the fieldName while calling populate method instead of the name of collection.(name of collectionn is required in the schema definition i.e., `userSchema`) | |
| log("$log5-", await userModel.findById("asfasf92h9sh9sf").populate("friends")); | |
| userModel.findByIdAndUpdate(id, updatedObject, {new: true}); //Though it is EQUIVALENT TO findOneAndUpdate(_id: id, ...) | |
| // By default, findByIdAndUpdate() returns the document as it was **before** update was applied. If you set new: true, findOneAndUpdate() will instead give you the object after update was applied. To change the default to true, use mongoose.set('returnOriginal', false);. | |
| userModel.findByIdAndRemove(id, options); // return Query | |
| // ? // userModel.findByIdAndRemove(id, ...) IS EQUIVALENT TO findOneAndRemove({ _id: id }, ...) | |
| await userModel.deleteMany({}); | |
| // ? Detele all documents in ^^ the collection modelUser. | |
| await userModel.collection.insertOne((desiredObjet = {})); | |
| await userModel.collection.insertMany((desiredObjet = {})); //To write many documents. | |
| await userModel.collection.bulkWrite((desiredObject = {})); //To write many documents. | |
| try { | |
| const userSaved = await new userModel({username: "superman9"}).save(); //This line just create the _id property for the object, and checks for any error acc. to schema. | |
| log("saveduser- ", userSaved); | |
| } catch (error) { | |
| log(`#me error: ${error.message} ==produced by== ${error.name}`); | |
| // ? Handle from here for failed attempt only according to the error that is produced, | |
| // ? you can send this eroor to frontend to, and do appropriate actions here only. | |
| } | |
| } | |
| main(); | |
| // ========================= | |
| function usingPromiseCallback() { | |
| new userModel({username: "barfillamaan22"}) //(1)This line just create the _id property for the object. | |
| .save() // (1)This method first checks the authenticity against the defined criteria in schema and (2)then tries to save accordingly, and (3)returns the object with additional __v property. | |
| .then((q) => log("Yikess..!!", q)) //(1)This method executes on succesful saving to database operation. | |
| .catch((err) => log(`==NAKED ERROR== "${err.message} ==produced by== ${err.name}"`)); | |
| } | |
| // ========================= | |
| //src: Ademola's abstract code for doing save and populate, sinle liner. | |
| // const savedBlog = await (await blog.save()) | |
| // .populate("user", { | |
| // username: 1, | |
| // name: 1, | |
| // _id: 1, | |
| // }) | |
| // .execPopulate(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment