Full-Stack Web Development with Vue.js and Node

(singke) #1
Introducing MongoDB Chapter 3

The output is as follows:


As you can see, we had two entries with the name Mike, but it only removed one. Similarly,


if we want to remove all the documents, we can just use:


> db.users.remove({})

All documents will be removed.


We talked about the basic ideas on how we can query the documents in Mongo. To find out
more details, visit https:/​/​docs.​mongodb.​com/​v3.​2/​tutorial/​query-​documents/​.


Introducing Mongoose


Mongoose is an elegant MongoDB object modeling library for Node.js. As I mentioned


earlier, MongoDB is a schemaless database design. While this has its own advantages,
sometimes we need to add certain validations as well, and this means defining the schemas


for our documents. Mongoose provides an easy way to add such validations and to
typecast the fields in a document.


For example, to insert data into a MongoDB document, we can use:


> db.posts.insert({ title : 'test title', description : 'test
description'})

Now, if we want to add another document and we want an extra field in that document, we


can use:


> db.posts.insert({ title : 'test title', description : 'test description',
category: 'News'})

This is possible in MongoDB because no schemas are defined. These types of documents


are also needed when building an application. MongoDB will silently accept any kind of
document. However, there are times when we need to have documents look similar in


order to behave in certain validations or to have a specific data type. In such situations,
Mongoose comes to the rescue. We can also leverage these features with raw MongoDB as


well, but writing validations in MongoDB is an extremely painful task. That's why


Mongoose was created.

Free download pdf