Mongoose With Node Js

No-SQL databases allow developers to send and retrieve data as JSON documents, instead of SQL objects. To work with MongoDB in a Node.js app, we can use . Mongoose.js connects your MongoDB clusters or collections with your Node.js app. Mongoose provides a lot of functionality when creating and working with schemas. The first difference between a Mongoose and a native-MongoDB application is that a module containing the schema and model must be created in the models directory.

In the case above we just have two fields, a string and a date. In the next sections, we will show some of the other field types, validation, and other methods. The rest of this tutorial shows how to define and access the Mongoose schema and models for the LocalLibrary website example.

The model we compiled in the last section contains all we need for interacting with the collection on the database. Middleware are functions or hooks that can be executed before or after standard Mongoose methods, like save() or find() for example. The ref property must be the name of the model we are referencing. We will see more about models later, but for now is enough to know a schema relates to one model only, and ‘Person’ is the model of the PersonSchema. The way to represent this in Mongoose is by saving the ID of the referenced document, mongoose.Schema.Types.ObjectId, not the object itself.

mongoose

Our story document now has an author referenced by the author document’s ID. In order to get the author information in the story results we use populate(), as shown below. If you specify a callback, as shown above, the query will execute immediately.

In addition to the “phone number” the following connection parameters may also be specified. When model.save() is called, there is a pre(‘save’, …) and post(‘save’, …) event that is triggered. mongoose bmx bike For the second parameter, you can pass a function that is called when the event is triggered. These functions take a parameter to the next function in the middleware chain.

We may also need to process the data in some way before saving it. To understand what is huffy mountain bike we first need to understand in general terms how MongoDB works. The basic unit of data we can save in MongoDB is a Document.