“Error: ‘TypeError: Cannot read properties of undefined (reading ‘collection’)”

huangapple go评论77阅读模式
英文:

Error: "TypeError: Cannot read properties of undefined (reading 'collection')"

问题

I'm trying to retrieve data from MongoDB atlas in Visual Studio Code, but I'm getting this error:

Mongo connected
--- TypeError: Cannot read properties of undefined (reading 'collection')
    at mongoDB (mernapp/backend/db.js:10:59)
    at Object.<anonymous> (mernapp/backend/index.js:5:1)
    at Module._compile (node:internal/modules/cjs/loader:1275:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1329:10)
    at Module.load (node:internal/modules/cjs/loader:1133:32)
    at Module._load (node:internal/modules/cjs/loader:972:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12)
    at node:internal/main/run_main_module:23:47

This is my db.js file:

const mongoose = require('mongoose');
const express = require("express");
const app = express();
const mongoURI = "mongodb+srv://varuag:xyz987@foodly.njjoa4i.mongodb.net/"
const mongoDB = async() => {
    try{
        mongoose.set('strictQuery', false)
        mongoose.connect(mongoURI)
        console.log('Mongo connected')
        const fetched_data = await mongoose.connection.db.collection("food_items");
        fetched_data.find({}, {projection: {}}).toArray(function(err, data){
            if(err) console.log('---', err);
            else console.log(data);
        })
    } catch(err) {
        console.log("---", err)
        process.exit();
    }
}
module.exports = mongoDB;

And, this is my index.js file:

const express = require("express");
const app = express();
const port = 5000;
const mongoDB = require("./db");
mongoDB();

app.get('/', (req, res) => {
    res.send("Hello World");
})

app.listen(port, () => {
    console.log(`The backend is listening on port ${port}`);
})

I tried changing

fetched_data.find({})

to

fetched_data.find({}, {projection: {}})

I'm new to this tech, so I asked bard and got this as a solution, but I'm still not getting any data from the database.

英文:

I'm trying to retrieve data from MongoDB atlas in Visual Studio Code, but I'm getting this error:

Mongo connected
--- TypeError: Cannot read properties of undefined (reading &#39;collection&#39;)
    at mongoDB (mernapp/backend/db.js:10:59)
    at Object.&lt;anonymous&gt; (mernapp/backend/index.js:5:1)
    at Module._compile (node:internal/modules/cjs/loader:1275:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1329:10)
    at Module.load (node:internal/modules/cjs/loader:1133:32)
    at Module._load (node:internal/modules/cjs/loader:972:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12)
    at node:internal/main/run_main_module:23:47

This is my db.js file:

const mongoose = require(&#39;mongoose&#39;);
const express = require(&quot;express&quot;);
const app = express();
const mongoURI = &quot;mongodb+srv://varuag:xyz987@foodly.njjoa4i.mongodb.net/&quot;
const mongoDB = async() =&gt; {
    try{
        mongoose.set(&#39;strictQuery&#39;,false)
        mongoose.connect(mongoURI)
        console.log(&#39;Mongo connected&#39;)
        const fetched_data = await mongoose.connection.db.collection(&quot;food_items&quot;);
        fetched_data.find({}, {projection: {}}).toArray(function(err, data){
            if(err) console.log(&#39;---&#39;, err);
            else console.log(data);
        })
    } catch(err) {
        console.log(&quot;---&quot;, err)
        process.exit();
    }
}
module.exports = mongoDB;

And, this is my index.js file:

const express = require(&quot;express&quot;);
const app = express();
const port = 5000;
const mongoDB = require(&quot;./db&quot;);
mongoDB();

app.get(&#39;/&#39;, (req, res) =&gt; {
    res.send(&quot;Hello World&quot;);
})

app.listen(port, () =&gt; {
    console.log(`The backend is listening on port ${port}`);
})

I tried changing

fetched_data.find({}) 

to

fetched_data.find({}, {projection: {}})

I'm new to this tech so I asked bard and got this as a solution but still not getting any data from database.

答案1

得分: 1

In your db.js file on line 8, add await as in the following code:

在你的db.js文件的第8行添加await,如下所示:

await mongoose.connect(mongoURI)

What's happening is you are trying to access the raw mongo instance and fetching data before the connection is made.

发生的情况是在建立连接之前尝试访问原始的Mongo实例并获取数据。

Reference: https://mongoosejs.com/docs/api/connection.html#Connection.prototype.db

参考链接:https://mongoosejs.com/docs/api/connection.html#Connection.prototype.db

UPDATE:

Regarding your comment below, the following reference says toArray() does not take in any parameters.

关于你下面的评论,以下参考链接表示toArray()不接受任何参数。

https://www.mongodb.com/docs/manual/reference/method/cursor.toArray/#mongodb-method-cursor.toArray

You should change your code to use the following.

你应该将代码更改为使用以下方式:

const data = fetched_data.find({}, {projection: {}}).toArray();
console.log(data);
英文:

In your db.js file on line 8 add await as in the following code:

await mongoose.connect(mongoURI)

What's happening is you are trying to access the raw mongo instance and fetching data before the connection is made.

mongoose.connection.db //The mongodb.Db instance, set when the connection is opened

Reference: https://mongoosejs.com/docs/api/connection.html#Connection.prototype.db

UPDATE:

Regarding your comment below the following reference says toArray() does not take in any parameters.

https://www.mongodb.com/docs/manual/reference/method/cursor.toArray/#mongodb-method-cursor.toArray

You should change your code to use the following.

const data = fetched_data.find({}, {projection: {}}).toArray();
console.log(data);

huangapple
  • 本文由 发表于 2023年5月14日 13:00:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76245892.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定