我正在node.js中编写快速应用程序,并且在更新此模型时遇到问题。
var reviewSchema = new mongoose.Schema({
comment: {
type: String,
trim: true,
max: 200
},
rating: { type: Number, trim: true, max: 10, min: 0 },
user: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
created: { type: Date, default:Date.now }
});
var eventSchema = new mongoose.Schema({
name: { type: String, trim: true, max: 30 },
venue: { type: String, trim: true, max: 30 },
critic_review: String,
user_reviews: [reviewSchema],
});
此路线定义如下......
app.js
app.put('/event/:id/reviews', routes.events.addReview)
激活此功能
路由/ events.js
// Route to update Event with a new Review
exports.addReview = function(req, res, next) {
if(!req.params.id) return next(new Error('No event ID.'));
req.models.User.findById(req.user, function(error, user) {
// check if user's username is available to this route
if (req.user.username){console.log(req.user.username)}
req.models.Event.findByIdAndUpdate(
_id = req.params.id,
{$push: {"user_reviews":
{comment: req.body.comment, // correct
rating: req.body.rating, // correct
user: req.user.username // causes error, see below
}}},
{safe: true},
function(err, results)
{
if (err) console.log(err);
});
res.redirect('/event');
});
}
应该更新事件模型。以下是玉石模板的一部分
视图/ event.jade
each review in item.user_reviews
li #{review.user} says: #{review.comment} #{review.rating} # {review.created}
在localhost:3000 / event
中提供以下输出says: test 5 Thu Jul 02 2015 17:51:53 GMT+0100 (GMT Daylight Time)
要检查#{review.user}是空还是空,我添加了条件控制台日志(event.js:第6行),它给出了控制台输出
myname
所以req.user.username可用,但如果我尝试$ push它我会收到此错误:
[错误:无法使尚未添加到阵列的子文档无效]
我也试过传递
user : req.session.passport.user
到$ push然后从模板中获取值,但这也不起作用。
我花了一些时间查找此错误消息,但我找不到任何有用的东西。如果有人能够对此有所了解,我将非常感激!谢谢你的阅读。
编辑
app.js
中的护照配置var User = require('./models/user');
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
// Registration
app.post('/register', function(req, res) {
User.register(new User({ email: req.body.email, username: req.body.username }), req.body.password, function(err, user) {
if (err) {
console.log(err);
return res.render('register', {info: "Sorry. That email already exists. Try again."});
}
passport.authenticate('local')(req, res, function() {
console.log('Attempting auth');
res.render('profile', { user: user });
//res.redirect('/');
});
});
});
// Login authentication
app.post('/login', passport.authenticate('local'), function(req, res) {
res.redirect('/');
});
app.js
中的应用曝光模型// Expose models to app.
app.use(function(req, res, next){
if( !models.Article || !models.User || !models.Event )
return next(new Error('No models.'));
req.models = models;
return next();
});