如何使用Mongoose访问预先存在的集合?

时间:2011-04-26 18:33:43

标签: mongodb node.js express mongoose

我在数据库question中有大量300个test个对象。我可以通过MongoDB的交互式shell轻松地与这个集合进行交互;但是,当我尝试通过Mongoose在express.js应用程序中获取集合时,我得到一个空数组。

我的问题是,如何访问此已存在的数据集而不是在快速重新创建数据集?这是一些代码:

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); });

输出:

null [] 0

7 个答案:

答案 0 :(得分:216)

Mongoose添加了在模式下指定集合名称的功能,或者在声明模型时作为第三个参数。否则,它将使用您映射到模型的名称给出的复数版本。

尝试类似以下内容的模式映射:

new Schema({ url: String, text: String, id: Number}, 
           { collection : 'question' });   // collection name

或模型映射:

mongoose.model('Question', 
               new Schema({ url: String, text: String, id: Number}), 
               'question');     // collection name

答案 1 :(得分:55)

如果有人只想要一个简单的复制粘贴插件功能,这里就是Will Nathan的回答的抽象:

function find (name, query, cb) {
    mongoose.connection.db.collection(name, function (err, collection) {
       collection.find(query).toArray(cb);
   });
}

只需要find(collection_name, query, callback);给出结果。

例如,如果我在集合'foo'中有一个文档{a:1}并且我想列出其属性,我会这样做:

find('foo', {a : 1}, function (err, docs) {
            console.dir(docs);
        });
//output: [ { _id: 4e22118fb83406f66a159da5, a: 1 } ]

答案 2 :(得分:18)

你可以做这样的事情,而不是你将访问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
        })
    });

});

答案 3 :(得分:14)

我遇到了同样的问题,并且能够使用现有的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);

答案 4 :(得分:6)

您确定已连接到数据库吗? (我问,因为我没有看到指定的端口)

尝试:

mongoose.connection.on("open", function(){
  console.log("mongodb is connected!!");
});

此外,您可以在mongo shell中执行“show collections”以查看数据库中的集合 - 也许尝试通过mongoose添加记录并查看它最终的位置?

从连接字符串的外观来看,您应该在“test”db中看到记录。

希望它有所帮助!

答案 5 :(得分:2)

至少对我来说不明显的是,当使用Mongoose的第三个参数来避免用一个具有相同名称的新集合替换实际集合时,new Schema(...)实际上只是一个占位符,并且不会干扰exisitng架构,所以

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);});

工作正常并返回所有字段 - 即使实际(远程)架构不包含这些字段。 Mongoose仍然希望它为new Schema(...),变量几乎肯定不会破解它。

答案 6 :(得分:1)

转到MongoDB网站,登录>连接>连接应用程序>复制>粘贴到'database_url' > 集合 > 在“集合”中复制/粘贴。

var mongoose = require("mongoose");
mongoose.connect(' database_url ');
var conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection error:'));
conn.once('open', function () {

conn.db.collection(" collection ", function(err, collection){

    collection.find({}).toArray(function(err, data){
        console.log(data); // data printed in console
    })
});

});

乐于助人。 ? 来自 RTTSS。