javascript - Mongo 无法与 Node.js 一起使用

标签 javascript node.js mongodb mongodb-query

我正在解决一个简单的问题,即使用 Node.js 在 Mongo 数据库中插入集合。但是我面临两个问题:

1. 当我在 .insert 函数
中使用 {safe: true} (如下: albums.insert(a1, {safe: false}, cb);
albums.insert(a2, {safe: false}, cb); )时,集合不会插入到数据库中,即它们不会打印在当我这样做时终端console.log(doc) (请看下面的程序)

2.程序不会自行结束,我必须按ctrl+c才能结束它,即使它有db.close()最后,我可以在终端上看到“here”,即 console.logged之后db.close()

非常感谢任何帮助,谢谢!

var Db= require('mongodb').Db,
Connection= require('mongodb').Connection,
Server= require('mongodb').Server,
async= require('async');

var host= "localhost";
var port= Connection.DEFAULT_PORT;

var db= new Db("PhotoAlbums", new Server(host, port, {auto_reconnect: true,
        poolSize: 20}), {w: 1});

var a1= {_id: "Travel", name: "Travel", title: "Travelogues", description:        
"This was great", date: "1/1/2014"}, 
a2= {_id: "friends", name: "friends", title: "Friends", description:   
"Random Pics", dat: "2/1/2014"};

var albums, photos;

async.waterfall([

function(cb)
{
    db.collection("Albums", cb);    
}, 

function (albums_coll, cb)
{
    albums= albums_coll;
    db.collection("Photos", cb);
},

function (photos_coll, cb)
{
    photos= photos_coll;
    albums.insert(a1, {safe: false}, cb);
},

function (doc, cb)
{ 
    console.log("1. Successfully wrote ");
    console.log(doc);
    albums.insert(a2, {safe: false}, cb);   
},

function (docs, cb)
{ 
    console.log("2. Successfully wrote ");
    console.log(docs);
    cb(null);
},

], function(err, results)
{ 
    if(err)
     console.log("ERROR!");
    db.close();
    console.log("here");
});

最佳答案

基本上您从未连接到数据库。 Db 对象需要调用 .open() 方法,并且所有交互都发生在该方法提供的回调中或“连接”事件处理程序中。

还有一些概念您在这里有点偏离主题,我想向您澄清。首先是修改后的列表:

var async = require('async'),
    MongoClient = require('mongodb').MongoClient;


MongoClient.connect('mongodb://localhost/test',function(err,db) {

  var a1 = {
    "_id": "Travel",
    "name": "Travel",
    "title": "Travelogues",
    "description": "This was great",
    "date": new Date("2014/01/01")
  },
      a2 = {
    "_id": "friends",
    "name": "friends",
    "title": "Friends",
    "description": "Random Pics",
    "date": new Date("2014/01/02")
  };

  var albums;

  async.waterfall(
    [
      function(cb) {
        db.collection("albums",cb);
      },

      function(albums_col,cb) {
        albums = albums_col;
        albums.insert(a1,cb);
      },

      function(doc,cb) {
        console.log("1. Successfully wrote");
        console.log(doc);
        albums.insert(a2,cb);
      },

      function(doc,cb) {
        console.log("2. Successfully wrote");
        console.log(doc);
        cb();
      }
    ],
    function(err,results) {
      if (err) throw err;
      db.close();
    }
  );
});

首先,您应该在新代码中使用 MongoClient。这是所有语言的标准实现。如果需要,您仍然可以使用 Server 对象,但连接字符串通常就足够了。或者:

MongoClient.connect( new Server( 
    "localhost",
    Connection.DEFAULT_PORT,
    { "auto_reconnect": true }
    { w: 1 }
),function(err,db) {

    {...}
});

另一部分是我删除了默认设置的选项。更改连接池选项对于这样的列表并没有真正的意义,但是驱动程序中已经内置了一个默认的 5 连接,而没有指定它。 “WriteConcern”或 { w: 1 } 也是默认值。

其次,在为文档指定的结构中,使用真实日期对象。这些将作为 BSON 存储的“日期”类型序列化到 MongoDB 中,并且当作为实际日期对象读取时它们也会返回到您的代码中。这就是您想要对日期执行的操作。否则这些只是字符串并且不是很有用。

不太喜欢为集合声明变量,而不是将参数传递给回调,但为了简洁起见,保持不变。

请注意,.insert() 方法的 WriteConcern 部分省略了 { safe: true }。除非您确实想要覆盖连接的设置(您应该很少想要),否则您可能只想使用默认值。 “安全”选项也已被弃用,因此您应该编写等效的 { w: 0 }

但最后要注意的是,如果您选择 { w: 0 } 那么您所期望的所写入文档的“响应”将不会返回。即使该值已写入数据库,也会被报告为 null。这是因为这种“不安全”的写入方式不需要数据库的任何确认。因此,您只是假设它在那里,因此可能需要默认值 { w: 1 } ,这意味着它已得到确认。

输出如预期:

1. Sccessfully wrote
[ { _id: 'Travel',
    name: 'Travel',
    title: 'Travelogues',
    description: 'This was great',
    date: Wed Jan 01 2014 00:00:00 GMT+1100 (AEDT) } ]
2. Sccessfully wrote
[ { _id: 'friends',
    name: 'friends',
    title: 'Friends',
    description: 'Random Pics',
    date: Thu Jan 02 2014 00:00:00 GMT+1100 (AEDT) } ]

当然,这取决于您所在的字符串化输出的实际时区。另请注意,new Date("2014/01/01")new Date("2014-01-01") 的形式不相等。第一个将把日期构造为 UTC 时区对象,第二个将在您的本地时区中构造。 MongoDB 将存储 UTC,因此最好确保您存储的任何数据都以这种方式构建。

关于javascript - Mongo 无法与 Node.js 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27474920/

相关文章:

JavaScript:Azure 函数 blob 绑定(bind)处理异常

javascript - 获取被调用者 Function.Arguments 之一的 Function.Arguments

node.js - npm 审计修复没有改变任何东西

node.js - Nodejs readline 给出一些错误

ruby - Mongoid:嵌入式文档的唯一索引

javascript - 在下拉菜单中转换菜单

java - 如何在 Java 和 Javascript 之间共享常量

javascript - 如何在控制台中获得更好的测试报告?

javascript - 你可以存储对 mongo 集合的引用吗?

java - 如何在 Mongodb (Spring) 上编写此聚合查询