【问题标题】:How to access a preexisting collection with Mongoose?如何使用 Mongoose 访问预先存在的集合?
【发布时间】:2011-08-13 06:47:41
【问题描述】:

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

我的问题是,我怎样才能访问这个已经存在的数据集,而不是在 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

【问题讨论】:

    标签: mongodb node.js express mongoose


    【解决方案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。

    【讨论】:

      【解决方案2】:

      如果有人只想要一个简单的复制粘贴加载项功能,这里是 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 } ]
      

      【讨论】:

      • 这在对 API 运行集成测试时非常有用
      • 嗨,这是原子操作吗?假设我尝试将文档保存在回调函数中。这会是原子的吗?
      【解决方案3】:

      您可以这样做,而不是访问 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
              })
          });
      
      });
      

      【讨论】:

      • 完美答案!
      【解决方案4】:

      至少对我来说,其他不明显的事情是,当使用 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);});
      

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

      【讨论】:

      • 它给我'集合名称必须是字符串'错误,编辑:作为'calvinfo'的答案,如果你想在模型构造函数中给出集合名称,你只需以字符串形式传递集合名称而不是对象模型。所以如果像这样编辑,你的答案将是正确的, var User = mongoose.model('User', new Schema({ url: String, text: String, id: Number}, 'users')); // 集合名称; User.find({}, function(err, data) { console.log(err, data, data.length);});
      【解决方案5】:

      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
      

      【讨论】:

      • 在文档中的什么地方可以找到这些信息?这确实有帮助,但没有地方解释复数。
      • 嗨,@calvinfo 如何在运行时更改集合名称?我有 5 个 UserSchema 集合,我想给每个集合一个不同的名称,例如:users_server1、users_server2、users_server3...
      • 请提供示例查询,例如与Model.collection.insert();..
      • 同样,我花了很多时间来解决这个问题,文档在这里找到mongoosejs.com/docs/guide.html#collection
      • 这对我有用。我有一个我 mongorestored 的用户集合。为了使用猫鼬访问它,我做了mongoose.connect("mongodb://localhost/fromlab"); var Schema = mongoose.Schema; var User = mongoose.model("User", new Schema({}), "users"); User.find({}, function(err, doc){ console.log((doc)) })
      【解决方案6】:

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

      【讨论】:

      • 这正是我想要的,因为 mongoose 没有任何 gridFS 支持。我使用这种方法从 gridfs (gridstore) 中获取文件元数据。只需将上面代码中的 question 替换为 fs.files 即可。
      【解决方案7】:

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

      尝试:

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

      另外,您可以在 mongo shell 中执行“显示集合”以查看您的数据库中的集合 - 也许尝试通过 mongoose 添加一条记录并查看它在哪里结束?

      从你的连接字符串看,你应该在“测试”数据库中看到记录。

      希望对你有帮助!

      【讨论】:

      • 有趣的是,当我尝试访问的数据位于question 集合中时,它实际上将信息存储在questions 集合中。 Mongoose 会自动将集合/型号名称复数吗?
      • 是的,我认为确实如此……哈!我自己才刚刚开始,所以我还没有探索所有的角落和缝隙......但我记得当我在谷歌群组中旋转时看到栗子微风。
      猜你喜欢
      • 2013-07-01
      • 1970-01-01
      • 2016-04-12
      • 2014-08-25
      • 2020-05-27
      • 2020-11-16
      • 1970-01-01
      • 2016-02-01
      • 2018-11-07
      相关资源
      最近更新 更多