简体   繁体   中英

Mongoose Model.save() hangs when called from node.js app

I'm trying to learn node and mongo in order to build a simple web app/teach myself a little bit more about web applications. However, when I call Model.save(), the continuation function never seems to execute, and the data isn't saved.

Here's what I have so far:

/* app.js */

var express = require('express')
  , app = express()
  , routes = require('./routes')
  , http = require('http')
  , path = require('path')
  , mongoose = require('mongoose')
  , db 
  , Track
  , models = require('./models.js');

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser('secretstuff'));
  app.use(express.session());
  app.use(app.router);
  app.use(require('less-middleware')({ src: __dirname + '/public' }));
  app.use(express.static(path.join(__dirname, 'public')));
  app.use(function(err, req, res, next){
    console.error(err.stack);
    res.send(500, 'Something broke!');
  });
});

models.defineModels(mongoose, function(){
  app.Track = Track = mongoose.model('Track');
  db = mongoose.createConnection('localhost','nextrak')
});

app.get('/', routes.index);

app.get('/dbTest', function(req, res){
  console.log("Here goes...");
  var t = new Track({
    name: "TestTrack",
    artist: "Artist",
    tags: ["test"],
    next: ["track1","track2"]
  });
  console.log("Test Track:");
  console.log(t);

  t.save(function(){
    if(err)
      console.log("Error! Couldn't complete dbTest successfully.");
    else
      console.log("Aw yiss, got dbTest working");
  })
});

http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});


/*models.js*/

function defineModels(mongoose, cont){
  var Schema = mongoose.Schema;
  Track = new Schema({
    'name': { type: String, index: true },
    'artist': String,
    'tags': [String],
    'next': [String],
  });
  mongoose.model('Track', Track);
  cont();
}

exports.defineModels = defineModels;

No errors are thrown, and the mongo logs indicate that 5 new connections are spun up when I launch my app. No new logs appear (except [clientcursormon] logs). The app prints out the following when I load /dbTest in Chrome:

Here goes...

  Test Track:
    { name: 'TestTrack',
      artist: 'Basik',
      _id: 5031606aa11cf95815000001,
      next: [ 'track1', 'track2' ],
      tags: [ 'test' ] }

Mongo appears to be configured correctly. When I have node run the simple "Getting Started" script that Mongoose walks you through, everything works correctly.

Can anyone point out what I'm doing incorrectly?

You haven't created a connection for Mongoose to use by default. Replace this:

db = mongoose.createConnection('localhost','nextrak')

With this:

db = mongoose.connect('localhost', 'nextrak');

Couple other nits:

  1. You're setting Track as a global variable in models.js
  2. You need to add a err parameter to your t.save callback.

First of all, if you only need one connection, you should use mongoose.connect().

Second, I think you're mixing up the track schema and track model. These are two separate things. new Schema() create a Schema object, which gets passed to mongoose.model(). The result of mongoose.model (which it seems you're discarding) is what you want to use when creating a new instance to store in the database, not the schema.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM