mongoose findOne()函数的作用是:找不到未定义的文件

wbrvyc0a  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(122)

实际上,我想在函数外使用gfs变量。但是我得到的是undefined。我在后端使用Node.js,并使用Express.js框架。请快速了解一下我在做什么。

const mongoose = require("mongoose"); // Version = 6.2.10
const Grid = require("gridfs-stream"); // Version = 1.1.1

// Creating the mongodb connection
const mongoURI = "mongodb://localhost:27017/test";
const conn = mongoose.createConnection(mongoURI);

// Init gfs
let gfs;

conn.once("open", async () => {
  gfs = Grid(conn.db, mongoose.mongo);
  gfs.collection("uploads");
  console.log(gfs); // Returns the Grid object
});
console.log(gfs); // Returns "undefined" ===> Need to solve the bug here.
mlnl4t2r

mlnl4t2r1#

我也遇到过类似的问题,但对我有效的是

const gfs = conn.once("open", () => {
  
  gfs = Grid(conn.db, mongoose.mongo);
  gfs.collection("uploads");
  return gfs;
});

相关问题