首页 文章

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

提问于
浏览
105

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

我的问题是,如何访问这个已经存在的数据集而不是在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); });

这输出:

null [] 0

6 回答

  • 50

    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
    
  • 14

    如果有人只想要一个简单的复制粘贴插件功能,那么这就是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 } ]
    
  • 6

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

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

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

    尝试:

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

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

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

    希望能帮助到你!

  • 204

    至少对我来说,其他一些不明显的是,当使用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(...) ,变量几乎肯定不会破解它 .

相关问题