Can we have full CRUD functionality with Mongoose?

tdd

#1

Question

Can we have full CRUD functionality with Mongoose?

Answer

So far in the lessons, we have been focusing on adding and finding documents from the database since our main focus is testing that it is working as expected, but Mongoose does have Create Read Update and Delete functionality as it works with MongoDB.
We saw the C, the R, and the U in CRUD with:

//the export of the model allows us to create
module.exports = mongoose.model('Dinosaur', DinosaurSchema);

// so we can have:
const dino = new Dinosaur({
				name: 'T-rex',
				count: 11,
				risk: 'High'
			});
// we can read the database and find one document:

DinosaurSchema.statics.findByName = function(name, callback) {
  return this.findOne({ name: name }, callback);
};

// and we can update a document from the database with our breed method we created
DinosaurSchema.methods.breed = function() {
  this.count = this.count + 1;
};

Although Mongoose has an updateOne and updateMany methods that already exist, our breed method is special because it does not require a value to be passed to update the count property of the document.

Mongoose also has a delete method for our models, for example if we wanted to delete one dinosaur, we could say for example that our dinosaurs were transitioning from the Jurassic to the Cretaceous era and so our Jurassic friends will have to evolve or go extinct, let’s delete a Pterodactyl:

/*since our model was dino, imagine we had the 
dinosaur already in the database
then we call the dino model and use deleteOne*/

dino.deleteOne({ name: "Pterodactyl"}); 

Passing the name is what will allow us to find and match the dinosaur to be removed from the database.

Now, we see how easy is to have full CRUD with Mongoose.