Getting NULL data from collection from MongoDB Atlas

﹥>﹥吖頭↗ 提交于 2021-02-11 13:41:43

问题


I have connected my code to MongoDB Atlas using Mongoose... even though the collection has a data in it its shows null in response.


I want to know the exact issue and troubleshoot it, because the collection has the data required

Collection details are in this image:

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

回答1:


It's because the mongoose instances in your Connectivity Code and Model are different and unrelated. One is connected (Connectivity), but the other (Model) is not. You've to use the same instance so export one mongoose and import that where required.

// 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


来源:https://stackoverflow.com/questions/55858975/getting-null-data-from-collection-from-mongodb-atlas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!