Step 5
We have secured the users
route so only an "admin" can access it! Next, let's secure the "notes" so only their author can access them. First, we must create an author attribute for notes and link it to the users' collection.
Update the server/model/User.js
file:
const mongoose = require("mongoose");
const NoteSchema = new mongoose.Schema({
title: { type: String, required: true },
text: { type: String, required: true },
+ author: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
});
const Note = mongoose.model("Note", NoteSchema);
module.exports = Note;
A note has an author, and an author is a user!
To represent this in Mongoose, we link the ID of the referenced document, mongoose.Schema.Types.ObjectId
, not the object itself. However, the ref
property must be the model's name we are referencing.