【发布时间】:2017-11-03 10:43:58
【问题描述】:
我有一个名为 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;
我正在打印出“IN HERE”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);
任何想法我哪里出错了?
【问题讨论】:
-
res.redirect('/campgrounds/' + campground._id);将在其他异步操作完成之前被调用。您需要将其放在回调“内部”。 -
好电话。不过还是解决不了问题。所以现在我没有被重定向,但仍然没有发生任何事情......
-
'mongoose.set('debug',true)将它添加到您的列表中,最好在建立连接之前。这将显示ratings.insert()是否真的被调用过。如果不是,则Rating的模型定义可能存在问题。 -
感谢您的提示!是的,它永远不会被调用
-
当我添加 Rating.find({}, function(err, res) { console.log("HERE"); });我确实得到了 console.log 和 Mongoose:ratings.find({}, { fields: {} })... 所以它是 create 的问题
标签: javascript node.js mongodb express mongoose