Skip to content
Related Articles

Related Articles

Mongoose Documents

View Discussion
Improve Article
Save Article
  • Last Updated : 29 Jun, 2022
View Discussion
Improve Article
Save Article

Mongoose is a MongoDB object modeling and handling for node.js environment. Mongoose Documents represent a one-to-one mapping to documents stored in the database in MongoDB. Each instance of a model is a document. A document can contain any type of data according to the model created.

The following functions are used on the Document of the Mongoose:

  • Retrieving: The document is retrieved by different model functions like findOne(), findById().
const doc = MyModel.findById(myid);
  • Saving: The document is saved by calling the save function. The function is asynchronous and should be awaited.
await doc.save()
  • Updating using save(): The document can be updated by the save() function as follows:
await MyModel.deleteOne({ _id: doc._id });

doc.firstname = 'gfg';
await doc.save();
  • Updating using queries: The document can be updated by the queries without calling the save function.
await MyModel.findByIdAndUpdate(myid,{firstname: 'gfg'},function(err, docs){});
  • Validating: The documents are validated once they are created before saving to MongoDB. 
const schema = new Schema({ name: String, age: Number});
const Person = mongoose.model('Person', schema);

let p1 = new Person({ name: 'gfg', age: 'bar' });
// Validation will be failed
await p1.validate();

let p2 = new Person({ name: 'gfg', age: 20 });
// Validation will be successful
await p2.validate();
  • Overwriting: The documents can be overwritten using the overwrite method.
const doc = MyModel.findById(myid);
doc.overwrite({ fullname: 'gfg' });
await doc.save();

Example: In the following example, we will create a model, save it to the database and then retrieve it, update the document and then save it using mongoose. We will be using node.js for this example. Node.js and npm should be installed.

Step 1: Create a folder and initialize it:

npm init

Step 2: Install mongoose in the project.

npm i mongoose

The project structure is as follows:

 

Step 3: Create a file called index.js. Inside the index.js, connect to MongoDB. Here the MongoDB Compass is used.

index.js

Javascript




const mongoose = require("mongoose");
  
// Database connection
mongoose.connect("mongodb://localhost:27017/geeksforgeeks", {});
  
// User model
const User = mongoose.model("User", {
  name: { type: String },
  age: { type: Number },
});
  
// Creating a new document
async function start() {
  let user1 = new User({
    name: "Geeks",
    age: 20,
  });
  user1.save().then(async (doc) => {
    if (doc) {
      console.log("The document is saved successfully");
      console.log(doc._id);
    }
  });
  let user2 = await User.findOne({ name: "Geeks" });
  user2.name = "GeeksforGeeks ";
  user2.save().then(async (doc) => {
    if (doc) {
      console.log("The document is updated successfully");
      console.log(doc._id);
    }
  });
}
start();


Step 4: Now run the code using the following command in the Terminal/Command Prompt to run the file.

node index.js

Output: The output for the code is as follows:

 

And the document in the MongoDB is as follows:

 

Reference: https://mongoosejs.com/docs/documents.html


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!