【问题标题】:Getting NULL data from collection from MongoDB Atlas从 MongoDB Atlas 的集合中获取 NULL 数据
【发布时间】:2019-09-15 10:59:40
【问题描述】:

我已使用Mongoose 将我的代码连接到MongoDB Atlas...即使集合中有数据,它的响应显示为空。


我想知道确切的问题并解决它,因为该集合具有所需的数据

收藏详情在这​​张图片中:

1. Connectivity Code -
const mongoose = require('mongoose')
const uri = "mongodb+srv://<user>:<password>@cluster0-3awwl.mongodb.net/";
mongoose.connect(uri, {
    dbName: 'bing_bot'
}).catch((e) => {
    console.log('Database connectivity error ', e)
})

2.Model-
const mongoose = require('mongoose')

const Student = mongoose.model('student', {
    StudentName: {
        type:String
    },
    Contact: {
        type:String
    },
    Email: {
        type:String
    },
    BNo: {
        type:String
    },
    Year: {
        type:String
    }
})
 module.exports = Student`enter code here`

3. Retrieve data -
Student.findById(_id).then((data) => {
        console.log('data: ', data)})


4. Using MongoCLient

const uri = "mongodb+srv://<user>:<password>@cluster0-3awwl.mongodb.net/bing_bot"
MongoClient.connect(uri, function(err, client) {
   if(err) {
        console.log('Error occurred while connecting to MongoDB Atlas...\n', err);
   }
   console.log('Connected...');
   const collection = client.db("bing_bot").collection("student");
   // perform actions on the collection object
   collection.findOne({
       "StudentName": "Test"
   }).then((d) => {
       console.log('data: ', d)
   })

   const data = collection.find()
   console.log('data:1 ', data)
   client.close();
});

【问题讨论】:

    标签: node.js mongodb heroku mongoose mongodb-atlas


    【解决方案1】:

    这是因为您的Connectivity CodeModel 中的mongoose 实例不同且不相关。一个是连接的(连接性),但另一个(模型)不是。您必须使用相同的实例,因此导出一个 mongoose 并在需要的地方导入。

    // connectivityCode.js
    const mongoose = require('mongoose')
    const uri = "mongodb+srv://<user>:<password>@cluster0-3awwl.mongodb.net/";
    mongoose.connect(uri, {
      dbName: 'bing_bot'
    }).catch((e)=>{
      console.log('Database connectivity error ',e)
    })
    
    module.exports = mongoose; // <-- exporting
    
    // model.js
    const mongoose = require('./connectivityCode.js') // <-- importing
    // rest of the code
    

    【讨论】:

    • 这个解决方案对我不起作用!但是同样的 ia 已经尝试使用 MongoClient(检查更新的问题)并且它工作但为什么不是 Mongoose
    • 如果我使用 mlabs 而不是 mongoDB atlas 它工作正常
    猜你喜欢
    • 2019-12-22
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    相关资源
    最近更新 更多