Open In App

Mongoose Documents

Last Updated : 19 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 1: 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
 
// 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:

 

Example 2: In this example, we will try to validate a document explicitly by using “validate” method of mongoose schema. Mongoose internally calls this method before saving a document to the DB.

Please modify the index.js file you created in example 1.

Filename: index.js

Javascript




const mongoose = require('mongoose')
 
// Database connection
    dbName: 'event_db',
    useNewUrlParser: true,
    useUnifiedTopology: true
}, err => err ? console.log(err) : console.log('Connected to database'));
 
const personSchema = new mongoose.Schema({
    name: {
      type: String,
      required: true
    },
    age: {
      type: Number,
      min: 18
    }
});
 
const Person = mongoose.model('Person', personSchema);
   
const person1 = new Person({ name: 'john', age: 'nineteen' });
 
(async () => {
    await person1.validate();
})();


Steps to run the application:

node index.js

Output:

 

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads