使用AJAX / Node.js / Express / Mongoose / MongoDB,数据通过ajax成功传递到node.js并正确记录,但只有第一篇文章保存在MongoDB中。
在第一篇文章之后发送帖子仍然记录所有新数据,但是控制台被保持在一个空行(光标静止不动)..在成功后发布!' console.log,跟随.save调用,但数据库没有收到新数据!?
只有在刷新网页或保存文件后(此后还会自动启动nodemon),才能保存新帖子。
这是控制台日志(最后一行的' |'代表悬挂光标..):
Server is starting
posting a new Message..from: 53aada6f8b10eb0000ec8a90
[ 'username1' ]
element: username1
To: username1
Message: testTwo
Created: Tue Jul 01 2014 15:53:57 GMT-0400 (EDT)
post success!
|
这里是Node.js / Express / Mongoose .post& .save:
router.route('/messages')
// create a message (accessed by POST @ http://localhost:4200/api/v1/messages)
.post(function(req, res) {
console.log('posting a new Message..from: ' + req.session.user );
var message = new Models.Message();
var toWhom = req.body.to;
console.log(toWhom); // [ 'user1', 'user2' ]
toWhom.forEach(toWhomLoop);
function toWhomLoop(element, index, array) {
console.log('element: ' + element); // 'user1'
message.to.push({
user : user,
username : element,
read :
{
marked : false,
datetime : null
},
updated : req.body.nowDatetime
}); // push: to MessageUserSchema [array]
}
message.from.push({
user : req.session.user,
username : req.session.username,
updated : req.body.nowDatetime
}); // push: from MessageUserSchema [array]
message.message = req.body.message;
message.created = req.body.nowDatetime;
console.log('To: ' + req.body.to);
console.log('Message: ' + req.body.message);
console.log('Created: ' + req.body.nowDatetime);
// save the message, and check for errors
message.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Message "' + message.message + '" Created' });
});
console.log('post success!');
})
进一步查看,并使用 sublime 突出显示闭包.. .post(函数(req,res){闭包({ })
不要突出显示两侧(开始或结束),除非从.post中删除以下元素:
message.from.push({
user : req.session.user,
username : req.session.username,
updated : req.body.nowDatetime
}); // push: from MessageUserSchema [array]
message.message = req.body.message;
message.created = req.body.nowDatetime;
console.log('To: ' + req.body.to);
console.log('Message: ' + req.body.message);
console.log('Created: ' + req.body.nowDatetime);
只有当所有从.post注释/剪切上面时,闭包突出显示..是否存在语法问题?
答案 0 :(得分:1)
尝试将save()
功能更改为:
// save the message, and check for errors
message.save(function(err, result) {
if (err) {
console.log(err);
res.send(err);
}
console.log("The result: ", result);
res.json({ message: 'Message "' + message.message + '" Created' });
});