我的 MongoDB 集合中有大约 30,000 个文档。并且一直致力于开发一个node.js脚本来仅检索具有特定字符串键值对的记录。
MongoDB 服务器上的此查询返回了我一直在寻找的确切结果:
db.getCollection('posts').find({authorName: "Ashwin-kumar"})
立即返回大约 33 个文档。同样,我有大约 40 位不同名字的作者。
这是我的 node.js 脚本,用于按作者姓名检索帖子(是的,它基于名称,一个字符串,因为这些作者没有 ID :( ):
var fs = require('fs'),
request = require('request'),
async = require("async"),
assert = require('assert');
_ = require('lodash'),
MongoClient = require('mongodb').MongoClient;
var db, postsCollection, postCol;
async.series([dbConnect, checkCollection, createMeta, dbClose], function(){
console.log("Executed all calls in series.");
process.exit(0);
});
function dbConnect(callback){
MongoClient.connect("mongodb://localhost:27017/jPosts", function(pErr, pDb) {
if(pErr) {
console.dir(pDb);
return 0;
}
db = pDb;
callback();
});
}
function dbClose(callback){
db.close(true, function (err) {
if (err) console.error(err);
else console.log("close complete");
callback();
});
}
function checkCollection(callback) {
db.collection('posts', function(err, collection) {});
postsCollection = db.collection('posts');
postCol = db.collection('posts');
callback();
}
function createMeta(callback){
var meta = [];
postsCollection.aggregate([
{
$group : {_id : "$authorName"}
}]).toArray(function(err, result) {
assert.equal(err, null);
async.forEachLimit(result, 1, function(pPost, callback) {
getPosts(pPost._id, callback);
}, function(err) {
console.log(err);
callback();
});
});
}
function getPosts(pAuthor, callback){
var cursor = postCol.find({ "authorName": pAuthor});
cursor.toArray(function(err,items){
if(err)
callback(err);
else
callback(null, items);
});
}
这似乎对我不起作用。 cursor.toArray() 除了永远等待之外什么也不做。是不是每个文档的字段太多了?
我尝试获取光标获取的文档的计数,效果很好。
function getPosts(pAuthor, callback){
var cursor = postCol.find({ "authourName": pAuthor});
cursor.count().then(function(items_count) {
console.log(items_count);
callback();
});
}
此外,我尝试了游标的 .each 方法来迭代获取的文档。但还没有运气。
function getPosts(pAuthor, callback){
var cursor = postCol.find({ "authourName": pAuthor});
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
console.dir(doc);
} else {
console.log(err);
}
});
}
我在这里遗漏了什么吗?还可以做些什么来使这项工作成功?我使用异步的方式有什么问题吗?
P.S:这里的想法是查询转储并为 jPost 集合中的作者生成 PDF。
P.S 2:这是一个示例文档
{
"_id" : ObjectId("571d36b55672f713fe346a66"),
"id" : 56517,
"authorName" : "Ashwin-kumar",
"comment_count" : 380,
"tagline" : "... Opinions you don't really need",
"vote_count" : 5152,
"exclusive" : null,
"post": [
],
"post_comments" : [
//comment_count objects
],
"date" : "2016-03-27"
}
(为了简洁起见,我省略了 post 和 post_comments 部分。)
最佳答案
试试这个:
var collection = db.collection("collection_name");
collection.find({authourName: "Ashwin-kumar"}).toArray(function (err,items) {
if (err) {
console.dir(err);
} else {
//do something with items array
console.dir(items);
}
});
关于javascript - nodejs和MongoDB的collection.find()没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36878886/