使用Nodejs查找()方法MongoDB

时间:2017-06-04 15:47:04

标签: node.js mongodb

我目前正在尝试查找具有一定价值' bar'在关键的foo'。使用mongodb和nodejs。

当我尝试运行时,我得到:  " TypeError:无法读取属性'找到'未定义"错误返回。

如果我尝试使用findOne(),它只会返回第一个文档,其文档的值为" bar"对于密钥" foo",但是有3个。

module.exports = function(app, db) {

app.get('/foo', (req, res)=>{

db.collection('barCollection').find({foo: {$all: ['bar']}}
,(err, item)=>{
 if (err) {
            res.send({'error':'An error has occurred'});
        } else {
            res.send(item);
        } 
    });
 });
};

由于

2 个答案:

答案 0 :(得分:1)

保罗是对的,你的代码中存在一些问题,这就是为什么它会返回null。

这里尝试这个片段。我使用2个文件进行演示。

<强> model.js

const mongoose = require('mongoose');

mongoose.connect('mongo_url');
var barSchema = new mongoose.Schema({
  // your schema
});

module.exports = mongoose.model('Bar', barSchema);

<强> main.js

var BarCollection = require('./models'); // assuming both files are in same directory.

BarCollection.find({foo: {$all: ['bar']}}
,(err, item)=>{
 if (err) {
            res.send({'error':'An error has occurred'});
        } else {
            res.send(item);
        } 
    });
 });
};

基本上我在这里尝试的是:

  1. 在单独的文件中分离MongoDB模型代码
  2. 在用于CRUD操作的API文件中导入mongo集合

答案 1 :(得分:0)

由于某种原因,

db.collection('barCollection')返回null。你需要找出原因,它可能在你的代码中的其他地方,因为你没有这里的设置逻辑。

我看看mongodb是否正确连接(即你实际连接到数据库的数据库实例是否正在运行),mongodb是否正在运行并且在你配置它的端口上可用,等等。