i've got Node.js server and with Exressjs/Mongoose im trying to insert some embedded documents to a document. Here is the code:

  • the node code:

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

    });

  • from a jquery im making POST request with the following code:

         $.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")}
        });   
    

When i make the POST request in the node console there is an error: Cannot call method 'push' of undefined. At the same point in Chrome the request is still "pending". And if i start the server again (even after 10sec) the request "arrive" and the record is inserted but with new session and im unable to get the user name (which was my initial idea). Did someone face this scenario?

Thanks! Stefan

有帮助吗?

解决方案

You should really put the code containing the connection to mongoose, as well as schema definitions outside the callback for the route. At the moment you'll re-connect to mongoose and re-define all schemas with each page request.

So the following code should stay outside the route callback:

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top