Express 应用程序 Nodejs 和 mongoose db / mongodb 入门

发布于 2024-11-15 06:08:50 字数 1236 浏览 2 评论 0原文

我一生都无法让猫鼬在我的 Express 应用程序中工作。我已经安装了 mongoose,还通过 NPM 安装了 mongodb(mongoose 文档没有说明是否需要单独使用 mongodb 或者如何启动和运行它)。

这是我使用的代码。

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

有人知道我做错了什么吗?我不明白我是否需要以某种方式单独启动 mongodb (看起来 mongoose.connect 函数启动了 mongodb 服务器,对吗?)

但是,当我启动我的应用程序时,什么也没有发生(它应该输出错误或当我保存测试帖子时已保存到我的控制台吗?

无论如何,我们将非常感谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

╰沐子 2024-11-22 06:08:50

MongoDB 是一个完全独立的服务,因此必须已经运行,nodejs 才能访问它。

您看不到任何输出的原因是您的程序在帖子完成之前结束,或者在这种情况下,由于无法到达 MongoDB 而超时。

编辑

如果您仍然好奇为什么在 MongoDB 未运行时没有看到任何输出,请停止 MongoDB,修改您的应用程序以包含:

// 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

并再次运行它。

认识到 Nodejs 与大多数编程环境不同,它在事件循环中运行程序,而事件循环仅在有事情要做时才运行,这一点至关重要。如果无事可做,nodejs就会退出。

由于您的 post.save() 启动了对 MongoDB 的新异步调用并立即返回,应用程序将立即退出,因为它没有其他事情可做。 (在幕后,post.save() 只是将一个新的事件处理程序添加到事件循环中,以监视调用是否完成。)

为了确保您的程序不会立即退出,我们添加了 process.stdin.resume( ) 它指示事件循环在每次传递时检查新输入(来自标准输入),从而有效地使您的程序永远运行。

基于 Nodejs 的网络服务器依赖相同的机制来连续运行,监视来自网络套接字的输入而不是标准输入。

<强>
我无法充分强调事件循环概念对于 Nodejs 编程的重要性。我估计人们报告的让 NodeJS 做他们需要的事情的 75% 或更多的问题可以归因于不理解事件循环以及它如何影响 NodeJS 编程模型!

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文