Getting the data from the referenced object in Moongoose

Issue

i have created two models i.e., User and todos. In todos schema i am referencing to user through

user: {
    id: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
    },

Now in the database, the object is created in the todo as user > id,I can display the id in ejs using details.user.id but i want to access the other properties of this user, like his name and email. Please help me

user schema:

const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    unique: true,
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  date: {
    type: Date,
    default: Date.now,
  },
  admin: Boolean,
});

const User = mongoose.model("User", UserSchema);

module.exports = User;

todo schema:

const mongoose = require("mongoose");
const todoTaskSchema = new mongoose.Schema({
  content: {
    type: String,
    required: true,
  },
  date: {
    type: Date,
    default: Date.now,
  },
  user: {
    id: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
    },
    user: String,
  },
});
module.exports = mongoose.model("TodoTask", todoTaskSchema);

Document in Mongoose

Solution

You can populate the user reference:

const task = await TodoTask.find({}).populate('user').exec()

Also, try to change your TodoTask schema declaration:

const todoTaskSchema = new mongoose.Schema({
  content: {
    type: String,
    required: true,
  },
  date: {
    type: Date,
    default: Date.now,
  },
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  },
});

You should then be able to access user property with task.user.<user-property>.

Finally, you should modify your view to display the name property from details.user directly:

<ul class="todo-list">
  <% todoTasks.forEach(details => { %>
  <li class="todo-list-item">
    <div class="todo-list-item-name"><%= details.content %></div>
    <a href="/edit/<%= details._id %>" class="edit">
      <span class="fas fa-edit"></span>
    </a>
    <a href="/remove/<%= details._id %>" class="remove">
      <span class="fas fa-times"></span> </a
    >by &nbsp;<%=details.user.name %>
  </li>
  <% }) %>
</ul>

Answered By – lpizzinidev

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published