问题
My goal is to use MongoDB's (2.4.4) text command from Node. It works fine from the command line. Based on this previous SO issue: Equivalent to mongo shell db.collection.runCommand() in Node.js, I tried using MongoJS (0.7.17) but can't make it go. Here is the code:
mongojs = require('mongojs');
var products = mongojs('localhost:27017/mydb').collection('products');
products.runCommand('text', {search: 'a'}, function (err, docs) {
...
});
docs returns undefined and err is null. I can execute a normal function such as products.find() fine... and I can execute the search on the MongoDB command line. Anyone know how to make this go?
BTW, here is what docs contains in the callback:
{
"queryDebugString": "||||||",
"language": "english",
"results": [],
"stats": {
"nscanned": 0,
"nscannedObjects": 0,
"n": 0,
"nfound": 0,
"timeMicros": 55
},
"ok": 1
}
BTW, if there's another approach to make this work with just the normal native driver, I'm fine with that.
回答1:
Using the native driver I can run a command off of the db object as follows:
var MongoClient = require("mongodb").MongoClient;
MongoClient.connect(database, function (err, db) {
if (!err) {
db.command({ distinct: "Messages", key: "session" }, function (err, result) {
//more code here
});
}
});
I noticed you are running the command off of the collection object, that might be the problem.
回答2:
Yo need to call the command inside the db object, not inside the connect object
MongoClient.connect(url, function (err, db) {
if (!err) {
var dbo = db.db();
dbo.command({ insert: "mycollection", documents: [{"test":1}]}, function
(err, result) {
if (err)
{
console.log(err);
}else
{
console.log("1 document inserted",result);
}
}
);
}
});
来源:https://stackoverflow.com/questions/18455217/mongodb-and-mongojs-cant-get-runcommand-to-work-for-text-queries