Question

Je ne peux pas pour la vie de me faire fonctionner la mangouste dans mon application express. Ive installé mangouste, et aussi mongodb via NPM (la documentation mangouste n'a pas précisé si mongodb était nécessaire séparément ou comment l'obtenir et en cours d'exécution).

Voici le code im en utilisant.

    var mongoose = require('mongoose');
    mongoose.connect('mongodb://127.0.0.1/my_database');

    var Schema = mongoose.Schema, ObjectId = Schema.ObjectId;

    var Comments = new Schema({
        title     : String
      , body      : String
      , date      : Date
    });

    var BlogPost = new Schema({
        author    : ObjectId
      , title     : String
      , body      : String
      , date      : Date
      , comments  : [Comments]
      , meta      : {
            votes : Number
          , favs  : Number
        }
    });

    var BlogPost = mongoose.model('BlogPost', BlogPost);
    var post = new BlogPost();
    post.title='blahblah';
    // create a comment
    post.comments.push({ title: 'My comment' });

    post.save(function (err) {
      if(err){
          throw err;
          console.log(err);
      }else{
          console.log('saved!');
      }
    });

Quelqu'un a une idée de ce que Im faire le mal? Je ne comprends pas si je dois en quelque sorte commencer MongoDB ou non séparement (il ressemble à la fonction mongoose.connect commence le droit du serveur MongoDB?)

Mais ya, rien ne se passe jamais quand je commence mon application (et il devrait être délivrer soit l'erreur ou sauvé! À ma console quand je sauvegarde le droit post test?

Enfin bref toute aide serait très apprécié!

Merci

Était-ce utile?

La solution

MongoDB is a completely separate service and so must already be running for nodejs to access it.

The reason you are not seeing any output is because your program ends before your post completes, or in this case, times out because it cannot reach MongoDB.

EDIT

If you are still curious why you didn't see any output when MongoDB wasn't running, stop MongoDB, modify your app to include:

// exit program in one minute with an error
// cancelled if we can successfully talk to MongoDB
var sentinel = setTimeout(function(){
    throw "failed to connect to MongoDB after one minute!";
}, 60*1000); // 60 seconds

post.save(function (err) {

  clearTimeout(sentinel); // cancel the timeout sentinel

  if(err){
      throw err;
      console.log(err); // won't occur since the throw will end the program
  }else{
      console.log('saved!');
  }
});

process.stdin.resume();  // read from stdin to keep program running

and run it again.

It's critical to realize that nodejs isn't like most programming environments in that it runs your program within an event loop which only runs as long as it has something to do. If there is nothing to do, nodejs will exit.

And since your post.save() starts a new asynchronous call to MongoDB and immediately returns, the app will immediately exit since there is nothing else for it to do. (Under the covers, post.save() simply adds a new event handler to the event loop that watches for the call to complete.)

To assure your program won't exit immediately, we add process.stdin.resume() which instructs the event loop to check for new input (from standard input) on each pass, effectively making your program run forever.

Nodejs-based network servers rely on the same mechanism to run continuously, watching for input from a network socket instead of standard input.

I cannot stress enough how crucial the event-loop concept is to programming in nodejs. I would estimate that 75% or more of the problems people report getting nodejs to do what they need can be attributed to not understanding the event loop and how it affects the nodejs programming model!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top