【问题标题】:How to Connect/Query Mongoose to an existing Database如何连接/查询 Mongoose 到现有数据库
【发布时间】:2019-05-31 11:52:22
【问题描述】:

我正在尝试将 Node/Express 服务器连接到现有的 MongoDB 数据库/集合。我已经成功连接到数据库。但是,设置要查询的模型/模式非常困难。

MongoDB 是 MongoDB Atlas,拥有一个包含超过 800,000 个文档的集合。单个集合的名称是“delitosCollection”。

我尝试了以下方法但没有成功:

var CrimeData = mongoose.model('DelitosCollection', new Schema({}),'delitosCollection');


mongoose.connection.on('open', function(ref){
    console.log("connected to the mongo server");

   CrimeData.find({}, (err,results) => {
       if(err){
           console.log("ERROR")
           throw err
       }
       console.log("results: ", results.length)
   } )
});

我知道连接正常,因为我收到了没有错误的 console.log。但是,results.length 在应该超过 800,000 时返回 0。在这方面花费了太多时间。

【问题讨论】:

标签: mongodb mongoose mongoose-schema mongoose-models


【解决方案1】:

为您要使用的每个集合创建一个空架构 然后创建一个模型以在您的项目中使用 该模型采用 3 个参数 1) 型号名称 2)模式名称 3)集合名称(来自mongodb图集)

这样

const mongoose = require('mongoose');
mongoose.connect('mongodb uri')
const userSchema = new mongoose.Schema({});
const User = mongoose.model('User', userSchema, 'user');

那么就可以正常使用模型了

User.find({})

【讨论】:

    【解决方案2】:

    您可以参考下面给出的答案,只需在架构中传递一个空对象 比如 db.model('users', new Schema({}))

    【讨论】:

      【解决方案3】:

      连接到 mongo 数据库

      // Connect to mongoDB
      mongoose.connect('mongodb://localhost/[yourDbName]',{useNewUrlParser:true})
          .then(function(){
              console.log('mongoDB connected');
          })
          .catch(function(){
              console.log('Error :');
          }) 
      

      之后你必须创建你的模式,然后只有你可以查询数据库

      像这样创建你的架构

      // Crimes Schema 
      const CrimeDetailsSchema= new Schema({
          first_name: {
              type: String,
              required: true
          },
          last_name: {
              type: String,
              required: true
          },
          email: {
              type: String,
              required: true
          }
      
      });
      
      const Profile = module.exports = mongoose.model('delitosCollection', CrimeDetailsSchema, 'delitosCollection');
      

      然后创建您的查询

      您可以在 mongoose 文档 here 中了解这一点

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-10-17
        • 2019-06-16
        • 1970-01-01
        • 2021-06-27
        • 2017-03-02
        • 1970-01-01
        • 2021-02-09
        相关资源
        最近更新 更多