【问题标题】:Mongodb-mongoose collections undefinedMongodb-mongoose 集合未定义
【发布时间】:2021-07-10 03:57:02
【问题描述】:

我是新手,正在练习 Mongoose 和 Mongodb 连接。我成功地将我的数据库连接到我的本地计算机并获得日志确认。我正在尝试在不通过猫鼬模式的情况下获取我的收藏,但出现错误:TypeError: Cannot read property 'collection' of undefined。我不知道我做错了什么。

代码如下:

require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const { Schema } = mongoose;

const app = express();
mongoose
  .connect(process.env.MONGODB_URI, {
    useUnifiedTopology: true,
    useNewUrlParser: true
  })
  .then(() => console.log("DB Connected!"))
  .catch(err => {
    console.log(err);
  });

var connection = mongoose.connection;

connection.db.collection("bags", function (err, collection) {
  collection.find({}).toArray(function (err, data) {
    console.log(data); // it will print your collection data
  })
});

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您正在尝试在与 MongoDB 建立连接之前访问数据库。 (连接DB是异步代码)

    另外,请阅读 - https://javascript.info/async-await


    mongoose
      .connect(process.env.MONGODB_URI, {
        useUnifiedTopology: true,
        useNewUrlParser: true
      })
      .then(() => {
        console.log("DB Connected!");
        var connection = mongoose.connection;
        // run logic once db is connected.
        connection.db.collection("bags", function (err, collection) { 
          collection.find({}).toArray(function (err, data) {
            console.log(data); // it will print your collection data
          })
        });
      })
      .catch(err => {
        console.log(err);
      });
    

    或者

    mongoose.connection.on('connected', err => { // will trigger connected event when connected to MongoDB
      var connection = mongoose.connection;
    
      connection.db.collection("bags", function (err, collection) {
        collection.find({}).toArray(function (err, data) {
          console.log(data); // it will print your collection data
        })
      });
    });
    

    【讨论】:

    • 我仍然不确定
    • @Krisna 你能打印到控制台connection.db 吗?
    • 我做到了。我得到这个命名空间:MongoDBNamespace { db: 'myFirstDatabase', collection: undefined }
    • @Krisna 你能打印到控制台connection.db.collection("bags") 吗?
    • 哦,好的:D。感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 2014-09-22
    • 1970-01-01
    • 2014-06-05
    相关资源
    最近更新 更多