Node.js mongodb中未定义集合
我正在尝试从mongodb集合中获取结果,但当我通过routes调用函数时,它表示未定义错误集合,有人能建议我提供帮助吗Node.js mongodb中未定义集合,node.js,mongodb,express,Node.js,Mongodb,Express,我正在尝试从mongodb集合中获取结果,但当我通过routes调用函数时,它表示未定义错误集合,有人能建议我提供帮助吗 var express = require('express'); var router = express.Router(); var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/mydb"; MongoClient.connect(url, funct
var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if(!err) {
console.log("We are connected");
}});
exports.getprofile = function (url,req, res) {
collection.find({}).toArray(function(err,res, docs) {
if(err){
res.send(err);
}else if(res.length){
console.log(res)
}
else{
console.log('no docs found');
}
res.send(res);
});
}
此处未声明变量(集合),因此只有您出现此错误。您需要使用正确的集合名称声明该变量 例如: 如果要在test模式下的users集合中查找记录,则需要遵循以下代码
var express=require('express');
var router=express.router();
var MongoClient=require('mongodb')。MongoClient;
变量url=”mongodb://localhost:27017/test";
var集合=null;
连接(url,函数(err,db){
如果(!err){
log(“我们已连接”);
collection=db.collection(“用户”);
}});
exports.getprofile=函数(url、req、res){
collection.find({}).toArray(函数(err、res、docs){
如果(错误){
res.send(err);
}else if(相对长度){
console.log(res)
}
否则{
console.log(“未找到文档”);
}
res.send(res);
});
}
注意:在测试架构下的用户集合中需要一些记录。必须首先获取集合对象,如下所述
var collection = db.collection("simple_document_insert_collection_no_safe");
// Insert a single document
collection.insert({hello:'world_no_safe'});
请参考以下链接了解更多详细信息
您没有在文件上方定义集合,但仍希望访问itI。我认为应该是
db.collection.find…
。当然,它应该是一个真实的集合名。Sergio,添加了db.collection.find,它说db不是found@nlr_p:事实上,db
在该点不可见。您暂时将其保存在MongoClient.connect的回调中,但您忽略它,并且不将其保存在任何位置。ohk您可以编辑我的代码吗