我有一个用户的索引路径。我需要计算他们在子文档中的记录。这是我的索引路线:
router.get('/', middleware.isLoggedIn, (req, res, next) => {
// get all users from db
User
.find({})
.populate('gifts')
.exec(function (err, allUsers) {
if (err) {
req.flash('error', err.message);
}
res.render('users/index', {
users: allUsers,
title: 'Users',
breadcrumbsName: 'Users'
});
});
});
我正在使用.populate,因为我理解它就像一个内部联接。所以在我的ejs中我想做一些像Total Gifts,以及所有giftAmount的总和。这是我的giftSchema
const schema = new Schema({
user: {
type: Types.ObjectId,
ref: 'User',
required: true,
index: true
},
..
giftAmount: Types.Number,
..
});
我这样做是否正确?我错过了什么?
更新。我正在更新文档以按请求获得用户架构。
const
mongoose = require('mongoose'),
Schema = mongoose.Schema,
Types = Schema.Types,
passportLocalMongoose = require('passport-local-mongoose');
const paymentPreference = {
paypalEmail:Types.String,
check: {
addressLine1: Types.String,
addressLine2: Types.String,
city: Types.String,
state: Types.String,
zipCode: Types.String
}
};
let UserSchema = new mongoose.Schema({
firstName: Types.String,
lastName: Types.String,
aliasFirstName: Types.String,
aliasLastName: Types.String,
username: Types.String,
phone: Types.String,
password: Types.String,
isAdmin: Types.Boolean,
addressLine1: Types.String,
addressLine2: Types.String,
city: Types.String,
state: Types.String,
zipCode: Types.Number,
profilePic: {
type: Types.String,
default: 'https://s.gravatar.com/avatar/0a07df079fd7a07e4cd0e5668835296c?s=80'
},
preferredPaymentMethod: {
type: Types.String,
enum: ['', 'paypal', 'check', 'deposit'],
default: ''
},
paymentPreference: {
type: paymentPreference
},
lastLoginDate: {
type: Date,
default: Date.now
}
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model('User', UserSchema);
答案 0 :(得分:0)
我可以做的是所谓的虚拟类型,并使用getter将其返回给我的模型!
UserSchema.virtual('giftCount').get(function () {
return this.gifts.length;
});