Chola Tech
Chola Tech

Reputation: 101

Not understanding the Mongoose Model?

I am currently in the process of learning the MEAN stack, and in my studies I am currently on Mongoose.

I have an issue understanding what is the model below used for:

var campgroundSchema = new mongoose.Schema({
	name: String,
	image: String
});
var Campground = mongoose.model("Campground", campgroundSchema);

Why is it needed if the MongoDB itself is a NoSQL database? The only explanation I can think of is that it is made so that you can use the standard functions such as find() and create().

Are there other ways to do these things?

Also a MORE IMPORTANT QUESTION: What does the first argument ("Campground") in the code above refer to? I can't find it anywhere in the database.

I've read the documentation and I still don't understand it.

Upvotes: 2

Views: 173

Answers (2)

Alex Wang
Alex Wang

Reputation: 358

MongoDB is a NoSQL database, which means the documents (their term for records) stored in the database are unstructured unlike SQL database. There are no set of fixed columns. A great example of a use case for MongoDB is if you're storing data for social media things like Facebook where data about a user can take many forms.

However, it lacks the ability to perform any data validation or provide some form of structure for its documents. If say you have a web service that takes food orders and a hacker manages to figure out how to send requests to make food order and decides to add another property that does not exist in your collection (equivalent to SQL's table), he/she will be able to do so due to the flexibility of MongoDB.

Mongoose solves this problem. It allows you to define something called a schema, which provides a backbone for how data inside a collection should look like. You can also use a schema to restrict data types, set the fields to be required when storing data, and much more as a result of using this tool. The side effect is that you get data validation and data structure all in one package.

If you didn't use Mongoose, you'd have to write all this validation code yourself. However, keep in mind that mongoose is not simply a validation and schema tool. It also is packed with lots of other features such as sorting data that is returned. Think of it as an add-on for MongoDB to make it even easier to use.

Upvotes: 4

Sajeetharan
Sajeetharan

Reputation: 222700

Even though MongoDB is a NOSQL database, you need Schema in the design because you can have a structure. It'is an object that defines the structure of any documents that will be stored in your MongoDB collection; it enables you to define types and validators for all of your data items.

In the above Campground is the name that you have given for the model which you can use to do the crud operations.

Upvotes: 1

Related Questions