首先,我的编程知识完全是前端的,但我正在尝试使用 Node、Express、Mongoose 和 MongoDB。我正在使用其他人的模板来尝试以正确的方式构建应用程序,但在连接这些点时我迷失了方向。我有以下 Jade :
form(method='post', action="/post/comment/" + post.id)
textarea(name='text')
input(type='submit', value='Save')
与routes/posts.js 文件中的内容相结合
app.post("/post/comment/:id", loggedIn, function (req, res, next) {
var id = req.param('id');
var text = req.param('text');
var author = req.session.user;
Comment.create({
post: id
, text: text
, author: author
}, function (err, comment) {
if (err) return next(err);
res.redirect("/post/" + id);
});
});
这是 models/comment.js :
var mongoose = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;
var createdDate = require('../plugins/createdDate');
var schema = mongoose.Schema({
text: { type: String, trim: true, validate: validateText }
, post: { type: ObjectId, index: true }
, author: String
})
function validateText (str) {
return str.length < 250;
}
schema.plugin(createdDate);
module.exports = mongoose.model('Comment', schema);
现在这可以正常工作,可以提交评论并将其保存在数据库中。问题是,我不想保存注释,而是保存函数操作后的 HTML。所以我尝试了:
var everything = $('.whatever').html();
$.post("/post/comment/:id", everything,
function(){
console.log('html saved!')
}
)
但是我收到了 POST http://localhost:3000/post/comment/:id 500 (Internal Server Error)
现在我知道我可能没有 id
变量,所以我尝试粘贴网址中的数字,这似乎没有错误,但没有出现在数据库中。我知道这可能不是一个具体的问题,而且我可能会完全错误地解决这个问题,但任何一般性的方向将不胜感激。谢谢。
最佳答案
您似乎遇到了很多问题。尝试查看以下内容:
您的路由器设置为接收到“/post/comment/:id”的帖子,但最后一个代码块中的帖子将发布到“/post/comments/:id”,其中评论是复数。这可能会导致 404。(检查浏览器 JavaScript 控制台的网络选项卡。它可能会在您没有意识到的情况下默默地失败)。
您的 500 错误可能是由于您直接发布了“:id”,而不是实际的标识符。许多 Node 应用程序都会设置一个 app.param() block 来验证这些参数,而您 friend 的模板在没有获得期望的数字时可能会崩溃。
您发布的数据必须与您将其保存到的模型的架构相匹配。架构中未命名的任何键都将在保存之前被删除,在您的情况下,如果没有键匹配,它将只是一个默认评论实例,并且根本不会保存。
希望有帮助!
关于javascript - 如何使用express/mongoose和客户端JS将HTML类发布到mongoDB集合中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20309238/