Step 9

Next, we create a model! Add the following to sampleNotes.js after the schema definition.

const Note = mongoose.model("Note", NoteSchema);

Notice the first argument to mongoose.model is the singular name for the entity your model is for. This is because Mongoose automatically looks for the plural, lowercased version of your model name as the collection that holds documents of that model. Therefore, the model "Note" will result in constructing a notes collection in the database.

Models are one of the constructs which Mongoose brings to the table. You can link a document schema to a model, then use the model to construct documents, as shown in the example below: (Make sure to import the faker package!)

Note.create(
  {
    title: faker.lorem.sentence(),
    text: faker.lorem.paragraph(),
  },
  (err, note) => {
    console.log(err ? err : note);
  }
);

The create method attached to a Mongoose model allows you to create documents of that model. It takes two arguments: an object representing the data to be saved in the database, and a callback function. It invokes the callback function by passing two arguments to it: an error (which will be null if there was no error) and the document created (which will be null if there was an error).

Save the file and run it. If all goes well, you will get a note document (which looks like a JSON) printed to the terminal.

Once the data is printed to the terminal, head over to MongoDB Atlas website. Find your cluster and click on the "Browse Collections" button.

You must be able to find the note we have just created!