开发者

express app nodejs and mongoose db / mongodb getting started

开发者 https://www.devze.com 2023-03-12 21:34 出处:网络
I cant for the life of me get mongoose working in my express app. Ive installed mongoose, and also mongodb via NPM (the mongoose documentation didn\'t state whether mongodb was required separately or

I cant for the life of me get mongoose working in my express app. Ive installed mongoose, and also mongodb via NPM (the mongoose documentation didn't state whether mongodb was required separately or how to get it up and running).

Here is the code im using.

    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!');
      }
    });

Anyone have any idea what Im doing wrong? I dont understand whether I need to somehow start mongodb seperately or not (it looks like the mongoose.connect function starts the mongodb server right?)

But ya, nothing ever happens when I start my app (and it should be outputting either the error or saved! to my console when I save the test post right?

Anyways any help would be very much appreciated!

Thanks


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消