Full-Stack Web Development with Vue.js and Node

(singke) #1
Introducing MongoDB Chapter 3

findByIdAndRemove()

This is the same as findOneAndRemove(), except that this always needs an id to be passed


as a parameter:


User.findByIdAndRemove(1, function(err){
if (err)
res.send(err)
res.send({
success: true
})
})

Did you find any difference in the code between findOneAndRemove() and the preceding


code for findByIdAndRemove()? If we look at the first parameter of this method, it only


takes a simple integer value, which is the document ID. Now, if we look into the


preceding findOneAndRemove() code, we will notice that we have passed an object in the


first parameter. That's because, for findOneAndRemove(), we can pass different


arguments other than ID as well. For example, we can also pass { name: 'Anita' } in


that parameter for findOneAndRemove(). But, for findByIdAndRemove(), as is obvious


from the method name, we don't need to pass an object but just an integer that denotes the
document's ID.


It finds a document with the mentioned ID in the parameter and removes that document
from the collections. Like findOneAndRemove(), this also returns the document that is


being deleted.


Adding validation with Mongoose


Validations in Mongoose are defined at the schema level. Validations can be set in both


strings and in numbers. Mongoose provides us with built-in validation techniques for
strings and numbers. Also, we can customize these according to our need as well. Since


validations are defined in the schemas, they are triggered when we hit the save() method


for any document. If we only want to test these validations, we can do that as well by


executing the validation method only via {doc}.validate().


validate() is also middleware, which means it has control when we are executing some


methods in an asynchronous way.

Free download pdf