Iterate Over The Document & amp; Sub-document in EJS

advertisements

I am creating a subdocument when I do my post for example on /gifts/new route. This new data is assigned to the user I select, and pass.

On my index route I have this:

Gift.find({}, function(err, allGifts) {
    if (err) {
        req.flash('error', err.message);
    } else {
        res.render('gifts/index', {
            title: 'Review Gifts',
            gifts: allGifts,
            breadcrumbsName: 'Gifts'
        });
    }
});

Back in the index.ejs template I'm doing a simple: <% gifts.forEach(function (user) { %> which is where my issue is. I need to find the user based on the _id: 586aef6ffe5cd14ab6532889 thats in the gifts object over iteration. As you may know that there are many gifts which has different user _id:

How do I do that? As I was writing this I had a thought which is to inside the } else { do a User.find{}, cb just so I can look up the user by that _id which is what tried but couldn't get working.

UPDATE

Here is my gift schema per request:

const mongoose = require('mongoose');

// Schema Setup
let giftSchema = new mongoose.Schema({
    username: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Gift'
        },
        username: 'String'
    },
    giftNumber: Number,
    date: Date,
    status: {
        review: String,
        accepted: {
            type: String,
            redeemed: Boolean
        },
        declined: String,
        expired: String,
        pending: String,
        paid: String
    },
    giftDescription: String,
    giftAmount: Number,
    giftCode: String,
    redeemCode: String,
    passCode: String,
    senderFirstName: String,
    senderLastName: String,
    giftMessage: String
});

module.exports = mongoose.model('Gift', giftSchema);

Here is the user:

const mongoose = require('mongoose'),
    passportLocalMongoose = require('passport-local-mongoose');

let UserSchema = new mongoose.Schema({
    firstName: String,
    lastName: String,
    aliasFirstName: String,
    aliasLastName: String,
    username: String,
    phone: String,
    password: String,
    isAdmin: Boolean,
    addressLine1: String,
    addressLine2: String,
    city: String,
    state: String,
    zipCode: Number,
    profilePic: {
        type: String,
        default: 'https://s.gravatar.com/avatar/0a07df079fd7a07e4cd0e5668835296c?s=80'
    },
    preferredPaymentMethod: {
        type: String,
        enum: ['', 'paypal', 'check', 'deposit'],
        default: ''
    },
    paymentPreference: {
        paypal: {
            email: {
                type: String,
                default: ''
            }
        },
        check: {
            addressLine1: {
                type: String,
                default: ''
            },
            addressLine2: {
                type: String,
                default: ''
            },
            city: {
                type: String,
                default: ''
            },
            state: {
                type: String,
                default: ''
            },
            zipCode: {
                type: Number,
                default: ''
            }
        },
        deposit: {
            routingOrTransit: {
                type: String,
                default: ''
            },
            accountNumber: {
                type: String,
                default: ''
            }
        }
    },
    lastLoginDate: {
        type: Date,
        default: Date.now
    }
});

UserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model('User', UserSchema);


1) fix Your Gift schema, see user attribute:

const
  mongoose = require('mongoose'),
  Schema = mongoose.Schema,
  Types = Schema.Types;

const schema = new Schema({
    user: {
      type: Types.ObjectId,
      ref: 'User',
      required: true,
      index: true
    },
    ...
});

module.exports = mongoose.model('Gift', schema);

2) change Your db query code:

Gift
  .find({})
  .populate('user')  // populate will join user model to .user attribute of gift item
  .exec(function(err, gifts) {
    if (err) {
        return res.status(500).send(err.message);
    } 

    res.render('gifts/index', {
      title: 'Review Gifts',
      gifts: gifts,
      breadcrumbsName: 'Gifts'
    });
  });

if You want gifts of dedicated user so:

Gift
  .find({user: req.user._id})
  .populate('user')
  .exec(function(err, gifts) {
    if (err) {
        return res.status(500).send(err.message);
    } 

    res.render('gifts/index', {
      title: 'Review Gifts',
      gifts: gifts,
      breadcrumbsName: 'Gifts'
    });
  });

3) and get necessary data in ejs template like this:

<% gifts.forEach(function(gift) { %>
  User ID: <%= gift.user._id %><br/>
  Username: <%= gift.user.username %><br/>
  Fullname: <%= gift.user.firstName %> <%= gift.user.lastName %><br/>
<% } %>