问题
Campaign data is storing except user reference in MongoDB campaign collection. How do I render only campaigns that were created by the user but not all campaigns by every user? I need this after the user logged in to website.
Campaign schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var campaignSchema = new Schema({
Title: {type: String},
Description: { type: String },
Rules: {} ,
Banner: { type: String },
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
});
module.exports = mongoose.model('Campaigns', campaignSchema);
User schema
const bcrypt = require('bcryptjs');
const crypto = require('crypto');
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
username: String,
email: { type: String, unique: true },
password: String,
phonenumber: Number,
passwordResetToken: String,
passwordResetExpires: Date,
emailVerificationToken: String,
emailVerified: Boolean,
snapchat: String,
facebook: String,
twitter: String,
google: String,
github: String,
instagram: String,
linkedin: String,
steam: String,
quickbooks: String,
tokens: Array,
profile: {
name: String,
gender: String,
location: String,
website: String,
picture: String
}
}, { timestamps: true });
/**
* Password hash middleware.
*/
userSchema.pre('save', function save(next) {
const user = this;
if (!user.isModified('password')) { return next(); }
bcrypt.genSalt(10, (err, salt) => {
if (err) { return next(err); }
bcrypt.hash(user.password, salt, (err, hash) => {
if (err) { return next(err); }
user.password = hash;
next();
});
});
});
/**
* Helper method for validating user's password.
*/
userSchema.methods.comparePassword = function comparePassword(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
cb(err, isMatch);
});
};
/**
* Helper method for getting user's gravatar.
*/
userSchema.methods.gravatar = function gravatar(size) {
if (!size) {
size = 100;
}
if (!this.email) {
return `https://gravatar.com/avatar/?s=${size}&d=blank`;
}
const md5 = crypto.createHash('md5').update(this.email).digest('hex');
return `https://gravatar.com/avatar/${md5}?s=${size}&d=blank`;
};
const User = mongoose.model('User', userSchema);
module.exports = User;
Route to render my campaigns created by the user. This is where I want to send campaign details created by the user.
router.get('/camptab', function(req, res, next) {
User.findById({ userid:req.user.id })
.populate('campaign').exec((err, campaign) => {
res.render('camptab', { camplist : campaign });
})
});
Campaign data is storing except user reference in MongoDB campaign collection. How do I render only campaigns that were created by the user but not all campaigns by every user? I need this after the user logged in to website.
来源:https://stackoverflow.com/questions/59915784/i-am-not-able-to-populate-tpaigns-data-that-reference-to-user-i-linked-campaign