简体   繁体   English

如何使用和尚和节点从mongodb集合中获取项目列表

[英]How to get a list of items from a mongodb collection using monk and node

I'm currently having trouble getting anything from my mongodb collection "media" with attributes "title" and "author" (among others, but these are just two for purpose of illustration). 目前,我无法从mongodb集合“媒体”中获取具有“标题”和“作者”属性的任何内容(还有其他两个,但仅出于说明目的而已)。 The following code prints "undefined to console". 以下代码显示“控制台未定义”。

var db = require('monk')(config['dbPath']);
var medialist = db.get('media');
var foundItems = medialist.find();
var firstFoundItem = JSON.stringify(foundItems[0]);
console.log(firstFoundItem);

Also, when the server is started, I get the following message in the console: 另外,启动服务器时,我在控制台中收到以下消息:

"{ [Error: Cannot find module '../build/Release/bson'] code'MODULE_NOT_FOUND'} js-bson: Failed to load c++ bson extension, using pure JS version" “ {[[错误:找不到模块'../build/Release/bson']代码'MODULE_NOT_FOUND'} js-bson:使用纯JS版本无法加载c ++ bson扩展名”

After searching that error message on Google, I've tried a few solutions including installing npm bson. 在Google上搜索该错误消息后,我尝试了一些解决方案,包括安装npm bson。 Is it just my code that isn't working, or is it the missing module (or both)? 仅仅是我的代码无法正常工作,还是缺少的模块(或两者皆有)?

Thanks, 谢谢,

musical 音乐

EDIT: Going by what @hassansin suggested about async calls, I tried the following, which now gives me "cannot read property 'then' of undefined at e:\\Dev\\BookWyrm\\api\\userRouter.js:16:43 编辑:按照@hassansin关于异步调用的建议,我尝试了以下操作,它现在使我“无法读取未定义的属性'then',位于e:\\ Dev \\ BookWyrm \\ api \\ userRouter.js:16:43

 var err;
    var params = req.params;
    mongoHandler.getMedia(err, params)
        .then(function(itemList) {
            if (!err) {
                var firstFoundItem = JSON.stringify(itemList[0]);
                console.log(firstFoundItem);
                res.sendFile('medialist.html', {
                    root: './public/views/'
                });
            } else {
                res.sendFile('errorpage.html', {
                    root: './public/views/'
                });
            }
        });
});

And mongoHandler is the following module: mongoHandler是以下模块:

var config = require('../config.json');
//var db = require('monk')('localhost:27017/bookwyrm');
var mongo = require('mongodb');

var server = new mongo.Server('localhost', 27017, {
    auto_reconnect: true
});

var db = new mongo.Db('bookwyrm', server);



function getMedia(err, params) {
    var callback = {};
    asyncGet(err, callback);

    if (!err) {
        return callback.items;
    } else {
        console.log("Connection or query to mongodb failed");
    }
}

function asyncGet(err, callback) {
    db.open(function(err, db) {
        if (!err) {
            db.collection('media', function(err, collection) {
                if (!err) {
                    collection.find(params).toArray(function(err, items) {
                        if (!err) {
                            db.close();
                            callback.items = items;
                        } else {
                            errorHandler(err, callback);
                        }
                    })
                } else {
                    errorHandler(err, callback);
                }
            })
        } else {
            errorHandler(err, callback);
        }
    });
}

function errorHandler(err, callback) {
    if (!db) {
        db.close()
    };
    callback.err = err;
}


module.exports.getMedia = getMedia;

You have couple of problems with your script. 您的脚本有几个问题。 First you didn't specify database name and second, find is an asynchronous operation, reading the return value of async method won't give you the result. 首先,您没有指定数据库名称,其次, find是一个异步操作,读取async方法的返回值不会得到结果。

var db = require('monk')('localhost:27017/dbname'); // <- database name
var medialist = db.get('media');
medialist.find({})
 .then(function(foundItems){   // <- use promise or callback to get result
   var firstFoundItem = JSON.stringify(foundItems[0]);
   console.log(firstFoundItem);
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM