背景:允许用户发布投票的应用程序。
我在 User 模型中填充对 Polls 模型的引用时遇到了一些麻烦。我正在使用 mongoose.populate 来尝试填充民意调查。在我的路线中,填充功能无法正常工作(返回的用户为空)。这是我的模型...
users.js:
// models/users.js
var mongoose = require('mongoose'),
Poll = require('./poll');
//define the schema for our user model
var userSchema = mongoose.Schema({
local:{
email: String,
password: String,
name: String
},
twitter:{
id: String,
token: String,
name: String
},
polls:[{type: mongoose.Schema.Types.ObjectId, ref:'Poll'}]
});
投票.js:
//load mongoose
var mongoose = require('mongoose'),
User = require('./user');
var pollSchema = mongoose.Schema({
name:String,
options:[String],
creator: {type:mongoose.Schema.Types.ObjectId, ref:'User'}
});
module.exports = mongoose.model('Poll', pollSchema);
这是我要在...中实施人口的路线
//require user and poll model
var User = require('../models/user'),
Poll = require('../models/poll');
app.post('/dashboard', isLoggedIn, function(req,res){
var poll = {name: req.body.name,
options: req.body.option,
creator: req.user.local.id};
//create new poll
var newPoll = new Poll();
newPoll.polls = poll;
//find the user with the request id and populate polls reference in User (UserSchema)
User.findById(req.user.local.id)
.populate('polls')
.exec(function(err,user){ // cant figure this out...
if(err){return err;}
console.log(user); // yields null
res.send({success:true, message: "Post Successful!"});
});
});
任何帮助、建议、想法将不胜感激。谢谢。