Mongoose Model.create not executing



我有一个叫Rating的猫鼬模型。当我想创建一个新的Rating时,我会转到post路由并调用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;

我正在打印"在这里"控制台日志。。。。但不是"创建评级"或错误。

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);

你知道我哪里错了吗?

首先,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">

相关内容

  • 没有找到相关文章

最新更新