Stefan Stoychev
Stefan Stoychev

Reputation: 5022

Can't insert to MongoDB with Node.js and Mongoose

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

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

Upvotes: 1

Views: 3390

Answers (1)

alessioalex
alessioalex

Reputation: 63683

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

Upvotes: 1

Related Questions