我有Node.js服务器和Exressjs / Mongoose我试图将一些嵌入式文档插入到文档中。这是代码:
节点代码:
app.post('/addcomment/:id', function(request, response){
var sys = require('util')
, mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
Schema = mongoose.Schema;
var CommentSchema = new Schema({
descr: String
});
var IssuesSchema = new Schema({
name: String,
comment: [CommentSchema]
});
mongoose.model('tasks', IssuesSchema);
var Issues = mongoose.model('tasks');
var taskid = request.params.id;
var user = "test";
var comment = request.param('descr');
Issues.findOne({_id: taskid}, function(err,item)
{
item.comment.push({descr:comment, posteddate: posteddate, user: user});
item.save();
response.writeHead(200,{"Content-Type": "text/plain"});
response.write(JSON.stringify(t));
response.end();
});
});
使用以下代码发出POST请求:
$.ajax({
type: 'POST',
url: "http://myhost/addcomment/123",
async: false,
timeout: 5000,
cache: false,
data: { descr: $('#comment').val() }
,success: function(data){
console.log(data);
,error: function(){console.log("err")}
});
当我在节点控制台中发出POST请求时出现错误:无法调用方法' push'未定义的。在Chrome中的同一点上,请求仍然是"等待"。如果我再次启动服务器(即使在10秒后),请求"到达"并插入记录,但新会话,我无法获取用户名(这是我最初的想法)。 有人面对这种情况吗?
谢谢! 斯蒂芬
答案 0 :(得分:1)
您应该将包含连接的代码放到mongoose,以及路由回调之外的架构定义。目前,您将重新连接到mongoose并使用每个页面请求重新定义所有模式。
因此以下代码应该保留在路由回调之外:
var sys = require('util')
, mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
Schema = mongoose.Schema;
var CommentSchema = new Schema({
descr: String
});
var IssuesSchema = new Schema({
name: String,
comment: [CommentSchema]
});
mongoose.model('tasks', IssuesSchema);