标签: node-mongodb-native

MongoDB不同,返回所有字段

我正在使用MongoDB和node-mongodb-native驱动程序.

我正在尝试返回具有不同属性的所有记录.

这似乎有效,但它只返回我正在检查的值是不同的值,而不是每个文档中的所有值.

这就是我试图只返回名称字段,我也试过没有它和变体,但它总是只返回数组中的item_id.

    this.collection.distinct("item_id", [{"name" : true}, {sold : {"$exists" : true}}], function(err, results) {
        if (err) {
            callback(err);
        } else {
            console.log(results);
        }
    });
Run Code Online (Sandbox Code Playgroud)

有关如何从每个文档获取所有数据的任何建议吗?

谢谢!

编辑:使用Map Reduce

所以,我只是使用node-mongodb-native来设置map reduce的开始,这是我到目前为止所拥有的:

    var map = function() {
        emit(this._id, {"_id" : this._id, "name" : this.name});
    }

    var reduce = function(key, values) {

        var items = [];

        values.forEach(function(v) {
            items.push(v);
        }); 

        return {"items" : items};
    }

    this.collection.mapReduce(map, reduce, {out: "res"}, function(err, results) {
        if (err) {
            console.log(err);
        } else {
            console.log(results);
        } …
Run Code Online (Sandbox Code Playgroud)

database mongodb node-mongodb-native

6
推荐指数
0
解决办法
3865
查看次数

MongoError:驱动程序与此服务器版本不兼容

我刚刚安装了Mongo,Node等,当我尝试通过我的nodejs服务器更新数据库时,我收到此错误:

MongoError: driver is incompatible with this server version
Run Code Online (Sandbox Code Playgroud)

以下是我的版本:

我有一切的最新版本,我搜索了节点mongodb驱动程序git,找出支持mongodb的版本,但我找不到任何东西:(

我还读了关于它的其他SO问题,它说要更新你的mongodb,但我的是最新版本!

有帮助吗?

mongodb node.js express mongoskin node-mongodb-native

6
推荐指数
1
解决办法
4989
查看次数

无法推断查询字段以在插入时设置错误

我正在尝试使用"findAndModify"来实现"getOrCreate"行为.我正在使用本机驱动程序在nodejs中工作.

我有:

var matches = db.collection("matches");
matches.findAndModify({
        //query
        users: {
            $all: [ userA_id, userB_id ]
        }, 
        lang: lang, 
        category_id: category_id
    }, 
    [[ "_id", "asc"]], //order
    {
        $setOnInsert: { 
            users: [userA_id, userB_id], 
            category_id: category_id, 
            lang: lang, 
            status: 0
        }
    }, 
    {
        new:true, 
        upsert:true
    }, function(err, doc){
        //Do something with doc
    });
Run Code Online (Sandbox Code Playgroud)

我想要做的是:"找到与指定用户,lang和类别的特定匹配...如果找不到,插入一个具有指定数据的新用户"

Mongo抛出这个错误:

Error getting/creating match { [MongoError: exception: cannot infer query fields to set, path 'users' is matched twice]
  name: 'MongoError',
  message: 'exception: cannot infer query fields to set, path …
Run Code Online (Sandbox Code Playgroud)

javascript mongodb mongodb-query node-mongodb-native

6
推荐指数
1
解决办法
777
查看次数

如何在nodejs中同步连接到mongodb

我想利用promises功能,我可以同步连接到mongodb,我可以通过将连接传递给不同的模块来重用连接.

这是我想出来的东西

class MongoDB {

    constructor(db,collection) {      
      this.collection = db.collection(collection);
    }

    find(query, projection) {
        if(projection)
            return this.collection.find(query, projection);
        else
            return this.collection.find(query);
    }
}

class Crew extends MongoDB {

    constructor(db) {        
        super(db,'crews');
    }

    validate() {

    }
}
Run Code Online (Sandbox Code Playgroud)

我想在我的初始代码中的某个位置设置一个连接,如下面的那个,然后重用不同类的连接,就像mongoose或monk那样,但只使用node-mongodb-native包.

MongoClient.connect(url)
          .then( (err,dbase) => {
                global.DB = dbase;
              });


var Crew = new CrewModel(global.DB);


Crew.find({})
   .then(function(resp) {
      console.log(resp);
   });
Run Code Online (Sandbox Code Playgroud)

现在,db在主MongoDB类中返回undefined,并且无法通过谷歌或文档调试这个.

编辑:我曾假设承诺是同步的但事实并非如此.

mongodb node.js node-mongodb-native

6
推荐指数
1
解决办法
2124
查看次数

如何使用 setOnInsert 在 mongodb 中放置创建/更新的字段?

我正在使用 nodejs 客户端来循环输入并创建一个将传递给bulkWrite操作的值数组:

  var updateVal = { sku: item.sku, name: item.name, updatedAt: new Date()};
  var insertVal = { sku: item.sku, name: item.name, createdAt: new Date(), updatedAt: new Date()};
  itemsToSave.push({
    updateOne: {
      filter: {
        sku: item.sku
      },
      //update: { $set: updateVal }, // works
      //update: { $setOnInsert: insertVal }, // works
      update: { $set: updateVal, $setOnInsert: insertVal }, // DOES NOT work
      upsert:true
    }
  });
Run Code Online (Sandbox Code Playgroud)

但由于某些原因,我不能混用$set$setOnInsert......当我运行它,什么也没有发生,它就像一个无操作。这是批量操作的限制吗?

我正在使用 node-mongodb-native/2.1 来处理 mongodb 3.0.7

setOnInsert的文档表明这应该是可能的:

...
  { …
Run Code Online (Sandbox Code Playgroud)

mongodb node.js node-mongodb-native

6
推荐指数
0
解决办法
1610
查看次数

MongoError:没有用户通过身份验证

我正在尝试使用mongodbNodeJS驱动程序编写脚本以将管理员用户和通用用户添加到MongoDB数据库- 版本3.0.1

我可以创建管理员用户,但不能创建数据库的普通用户.我总是得到MongoError: there are no users authenticated.通过文档,验证用户的唯一方法是通过URL.我已经从指定的路径完全删除了数据库,尝试了多次,仍然,我被卡住了.

这是我到目前为止所得到的,

const MongoClient = require('mongodb').MongoClient;
const format = require('util').format;
const config = require("./config.json");

var adminUser = process.argv[2],
adminPassword = process.argv[3],
url = `mongodb://${config.database.location}:${config.database.port}`,
authURL = `mongodb://%s:%s@${config.database.location}:${config.database.port}/?authMechanism=SCRAM-SHA-1&authSource=admin`;

if (!adminUser || !adminPassword) {
   throw new Error("Please enter administrator username and password!\nUsage:\tnode init.js <adminUserName> <adminPassword>\n\n");
}

MongoClient.connect(url, function (err, client) {
    if (err) throw err;
    console.log("Connected successfully to server");
    const db = client.db(config.database.name);
    var adminDb = db.admin();
    adminDb.addUser(adminUser, adminPassword, { …
Run Code Online (Sandbox Code Playgroud)

mongoose mongodb node.js node-mongodb-native

6
推荐指数
1
解决办法
9470
查看次数

使用适用于 Node JS 的 mongodb 本机驱动程序记录所有查询

我对 MongoDB 比较陌生。起初我使用猫鼬,但现在我决定放弃它。我立即遇到了以下问题:我无法理解如何将所有执行的查询打印到控制台。

在猫鼬中,这可以像编写 mongoose.set('debug', true) 一样简单,但是如何使用本机驱动程序来做到这一点?

我在文档中阅读了有关 Logger 的内容,但输出对我来说似乎完全不可读。是否可以调整输出,或者我应该以某种方式解析它?

javascript mongodb node.js node-mongodb-native

6
推荐指数
1
解决办法
1036
查看次数

向 Node.js MongoDB API 添加缓存?

我的 node.js API 对 MongoDB 运行一些昂贵的“组”查询,例如使用:

app.get('/group/:collection', function(req, res) {
    [...]
    db.collection("indicators").group(keys, conds, { value : 0 } [...]
Run Code Online (Sandbox Code Playgroud)

这里有哪些相当容易实现的缓存解决方案?

caching mongodb node.js node-mongodb-native

5
推荐指数
1
解决办法
4413
查看次数

NodeJS 应用程序中 Mongo 连接流意外关闭

我有一个 NodeJS 应用程序(使用 node-mongodb-native 驱动程序版本 2.1),它执行以下操作:

  1. 打开与 MongoDB 的连接。
  2. 查询集合(batchSize 设置为 1000)。此查询返回大约 1,300,000 个文档,这些文档是我自己验证的。
  3. 由于文件太多,无法放入 bson 响应中(如果我没记错的话,大约 16mb),我使用stream()游标对象上的函数来流式传输结果。
  4. 我将 1000 个文档分批上传到我的 Amazon CloudSearch 索引。

一切都按预期进行 - 文档已成功上传到我的 AWS 服务,一切都很好。

但是,一旦传输了 85,000 个文档,流就会发出该end事件。它始终如一地执行此操作,并且不会引发任何错误。通常我会把这归因于超时之类的事情,但事实上,每次上传 85,000 个文档然后立即结束/关闭流时都会发生这种情况,这让我觉得出了什么问题。

我的代码如下:

var options = {
    socketTimeoutMS: 120000,
    connectTimeoutMS: 120000,
    keepAlive: 1
};
var url = "www.myMongoAddress.com";
mongo.connect(url, options, function(err, db) {
    var collection = db.collection('myCollection');
    var stream = collection.find({mySearch: 'criteria'}).batchSize(1000).stream();
    var batch = [];    
    var total = 0;

    stream.on('end', function() {
        console.log('stream …
Run Code Online (Sandbox Code Playgroud)

mongodb amazon-web-services node.js node-mongodb-native

5
推荐指数
1
解决办法
1163
查看次数

TypeError:Grid不是构造函数.Mongodb节点驱动程序

我正在学习使用mongdb gridfs和nodejs驱动程序.我第一步陷入困境.

var MongoClient = require('mongodb').MongoClient;
var Grid = require("mongodb").Grid;

MongoClient.connect("mongodb://localhost:27017/kkdb", function(err, db) {
   if(err) return console.log("error in connection:>>>>>>>>>>>>>>> ", err); 

   var grid = new Grid(db, 'fs');
   var buffer = new Buffer("Hello world");

   grid.put(buffer, {metadata:{category:'text'}, content_type: 'text'}, function(err, fileInfo) {
       if(!err) {
           console.log("Finished writing file to Mongo");
       }
   });
});
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时,它显示错误:TypeError: Grid is not a constructor

mongodb node.js gridfs node-mongodb-native

5
推荐指数
1
解决办法
456
查看次数