Open In App

Mongoose Documents

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:



const doc = MyModel.findById(myid);
await doc.save()
await MyModel.deleteOne({ _id: doc._id });

doc.firstname = 'gfg';
await doc.save();
await MyModel.findByIdAndUpdate(myid,{firstname: 'gfg'},function(err, docs){});
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();
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




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:

 

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




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


Article Tags :