node.js 如何使用 Mongoose 访问预先存在的集合?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5794834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access a preexisting collection with Mongoose?
提问by theabraham
I have a large collection of 300 questionobjects in a database test. I can interact with this collection easily through MongoDB's interactive shell; however, when I try to get the collection through Mongoose in an express.js application I get an empty array.
我question在一个数据库中有300 个对象的大量集合test。我可以通过 MongoDB 的交互式 shell 轻松地与这个集合进行交互;但是,当我尝试在 express.js 应用程序中通过 Mongoose 获取集合时,我得到一个空数组。
My question is, how can I access this already existing dataset instead of recreating it in express? Here's some code:
我的问题是,如何访问这个已经存在的数据集而不是在 express 中重新创建它?这是一些代码:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/test');
mongoose.model('question', new Schema({ url: String, text: String, id: Number }));
var questions = mongoose.model('question');
questions.find({}, function(err, data) { console.log(err, data, data.length); });
This outputs:
这输出:
null [] 0
回答by calvinfo
Mongoose added the ability to specify the collection name under the schema, or as the third argument when declaring the model. Otherwise it will use the pluralized version given by the name you map to the model.
Mongoose 添加了在模式下指定集合名称的功能,或者在声明模型时作为第三个参数。否则,它将使用您映射到模型的名称给出的复数版本。
Try something like the following, either schema-mapped:
尝试类似以下的操作,或者模式映射:
new Schema({ url: String, text: String, id: Number},
{ collection : 'question' }); // collection name
or model mapped:
或模型映射:
mongoose.model('Question',
new Schema({ url: String, text: String, id: Number}),
'question'); // collection name
回答by Michael Taufen
Here's an abstraction of Will Nathan's answer if anyone just wants an easy copy-paste add-in function:
如果有人只想要一个简单的复制粘贴加载项功能,这里是 Will Nathan 的回答的抽象:
function find (name, query, cb) {
mongoose.connection.db.collection(name, function (err, collection) {
collection.find(query).toArray(cb);
});
}
simply do find(collection_name, query, callback);to be given the result.
简单地做得到find(collection_name, query, callback);结果。
for example, if I have a document { a : 1 } in a collection 'foo' and I want to list its properties, I do this:
例如,如果我在集合 'foo' 中有一个文档 { a : 1 } 并且我想列出它的属性,我会这样做:
find('foo', {a : 1}, function (err, docs) {
console.dir(docs);
});
//output: [ { _id: 4e22118fb83406f66a159da5, a: 1 } ]
回答by Leo Ribeiro
You can do something like this, than you you'll access the native mongodb functions inside mongoose:
您可以执行这样的操作,而不是访问 mongoose 中的本机 mongodb 函数:
var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost/local');
var connection = mongoose.connection;
connection.on('error', console.error.bind(console, 'connection error:'));
connection.once('open', function () {
connection.db.collection("YourCollectionName", function(err, collection){
collection.find({}).toArray(function(err, data){
console.log(data); // it will print your collection data
})
});
});
回答by Will Nathan
I had the same problem and was able to run a schema-less query using an existing Mongoose connection with the code below. I've added a simple constraint 'a=b' to show where you would add such a constraint:
我遇到了同样的问题,并且能够使用现有的 Mongoose 连接和下面的代码运行无模式查询。我添加了一个简单的约束 'a=b' 来显示您将在哪里添加这样的约束:
var action = function (err, collection) {
// Locate all the entries using find
collection.find({'a':'b'}).toArray(function(err, results) {
/* whatever you want to do with the results in node such as the following
res.render('home', {
'title': 'MyTitle',
'data': results
});
*/
});
};
mongoose.connection.db.collection('question', action);
回答by busticated
Are you sure you've connected to the db? (I ask because I don't see a port specified)
你确定你已经连接到数据库了吗?(我问是因为我没有看到指定的端口)
try:
尝试:
mongoose.connection.on("open", function(){
console.log("mongodb is connected!!");
});
Also, you can do a "show collections" in mongo shell to see the collections within your db - maybe try adding a record via mongoose and see where it ends up?
此外,您可以在 mongo shell 中执行“显示集合”以查看数据库中的集合 - 也许尝试通过 mongoose 添加记录并查看它的结束位置?
From the look of your connection string, you should see the record in the "test" db.
从连接字符串的外观来看,您应该会在“测试”数据库中看到该记录。
Hope it helps!
希望能帮助到你!
回答by Bart
Something else that was not obvious, to me at least, was that the when using Mongoose's third parameter to avoid replacing the actual collection with a new one with the same name, the new Schema(...)is actually only a placeholder, and doesn't interfere with the exisitng schema so
至少对我来说,其他不明显的是,当使用 Mongoose 的第三个参数来避免用同名的新集合替换实际集合时,new Schema(...)实际上只是一个占位符,并不会干扰存在架构所以
var User = mongoose.model('User', new Schema({ url: String, text: String, id: Number}, { collection : 'users' })); // collection name;
User.find({}, function(err, data) { console.log(err, data, data.length);});
works fine and returns all fields - even if the actual (remote) Schema contains none of these fields. Mongoose will still want it as new Schema(...), and a variable almost certainly won't hack it.
工作正常并返回所有字段 - 即使实际(远程)架构不包含这些字段。Mongoose 仍然希望它作为new Schema(...),并且变量几乎肯定不会破解它。

