我有一个名为Rating的猫鼬模型。当我想创建一个新的评级时,我会转到后期路线并致电Rating.create。出于某种原因,Rating.create永远不会被执行。我从别人那里复制了我的代码,那个人的代码正在运行。因此,我必须在我的应用程序的其他地方遗漏一些东西。有什么想法吗?
Ratings.js路线
var express = require("express");
var router = express.Router({mergeParams: true});
var Campground = require("../models/campground");
var Rating = require("../models/rating");
var middleware = require("../middleware");
router.post('/', middleware.isLoggedIn, function(req, res) {
Campground.findById(req.params.id, function(err, campground) {
if(err) { console.log(err); }
console.log("REQ.BODY.RATING: ", req.body.rating);
if (req.body.rating) {
console.log("IN HERE");
Rating.create(req.body.rating, function(err, rating) {
if(err) { console.log(err); }
console.log("Creating rating");
// do stuff
req.flash("success", "Successfully added rating");
});
} else {
req.flash("error", "Please select a rating");
}
res.redirect('/campgrounds/' + campground._id);
});
});
module.exports = router;
我正在"在这里"打印出console.log ....但不是"创建评级"一个或错误。
Ratings.js模型
var mongoose = require("mongoose");
var ratingSchema = new mongoose.Schema({
rating: Number,
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
});
module.exports = mongoose.model("Rating", ratingSchema);
我出错的任何想法?
答案 0 :(得分:0)
首先,if语句太多了,试试这种方法
router.post('/', middleware.isLoggedIn, function(req, res) {
Campground.findById(req.params.id, function(err, campground) {
if(err) { console.log(err); }
else if (req.body.rating) {
console.log("IN HERE");
Rating.create(req.body.rating, function(err, rating) {
if(err) { console.log(err); }
console.log("Creating rating");
rating.author.id = req.user._id;
rating.author.username = req.user.username;
rating.save();
campground.ratings.push(rating);
campground.save();
// do stuff
req.flash("success", "Successfully added rating");
});
} else {
req.flash("error", "Please select a rating");
}
res.redirect('/campgrounds/' + campground._id);
});
});
并确保在ejs文件中将变量命名为数组Object,因此它将基于该对象创建它"它只能使用您需要传入数组的数字变量来创建它以便将其转换为进入DB"中的Java对象,就像我们在评论中所做的那样:
<input class="form-control" type="text" name="comment[text]" placeholder="text">
<input class="form-control" type="text" name="rating[rating]" placeholder="text">