迭代文档& EJS中的子文档

时间:2017-01-03 00:41:47

标签: express mongoose

当我在/ gifts / new route上发帖时,我正在创建一个子文档。这个新数据被分配给我选择的用户并传递。

在我的索引路线上,我有这个:

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

回到index.ejs模板我做的很简单:<% gifts.forEach(function (user) { %>这就是我的问题所在。我需要在迭代过程中根据gifts对象中的_id: 586aef6ffe5cd14ab6532889找到用户。你可能知道有很多礼物有不同的用户_id:

我该怎么做?在我写这篇文章的过程中,我想到了} else {User.find{}, cb内部的问题,这样我就可以通过_id来查找用户,这是尝试但无法正常工作的。

更新

以下是每个请求的礼物架构:

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);

以下是用户:

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);

2 个答案:

答案 0 :(得分:1)

1)修复您的Gift架构,请参阅user属性:

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)更改您的数据库查询代码:

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'
    });
  });

如果你想要专用用户的礼物,那么:

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)并在ejs模板中获取必要的数据,如下所示:

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

答案 1 :(得分:0)

听起来你想从数组中获取一个对象。我假设gifts是一个对象数组。所以我会使用.find()

find与常规对象一起使用的示例:

var inventory = [
	    {name: 'apples', quantity: 2},
	    {name: 'bananas', quantity: 0},
	    {name: 'cherries', quantity: 5}
	];

var item = inventory.find(function(item){
	return item.name = "apples"
})
console.log(item)

您可能希望对gifts执行相同操作,但对EJS使用<%%>

您可能还需要gifts.toObject().find()如果您直接从猫鼬获取文件

编辑:我认为您在文档上使用toObject()而不是数组。我有几次没有出现文档,但是当我使用toObject时它出现了。