首页 > 解决方案 > Mongoose 模型查询挂在节点中

问题描述

我有一个数据库文件,我在其中为 mongo 设置模式/模型并导出它们。每当我在其他文件中引用模型进行查询时,然后在节点中运行该文件,它就会挂起。我取回了我的数据,但我必须手动关闭节点。我已经尝试过其他解决方案,例如mongoose.disconnect()在我的数据库文件末尾,但这会破坏我的查询。

数据库.js

const mongoose = require('mongoose')

mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true, useUnifiedTopology: true })

const exampleSchema = new mongoose.Schema({
  name: String,
  stuff: {}
})

const Example = mongoose.model('Example', exampleSchema)

module.exports = {
  Example
}

函数.js

const { Example } = require('../database')

const doSomething = async (name) => {
  const data = await Example.find({ name: name })
}

doSomething('jwhunt19')

标签: javascriptnode.jsmongodbmongoose

解决方案


试试这样:

const mongoose = require('mongoose');
const connection = mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true, useUnifiedTopology: true })

const exampleSchema = new mongoose.Schema({
    name: String,
    stuff: {}
  })
const doSomething = async (name) => {
  const data = await Example.find({ name: name })
}

doSomething('jwhunt19')

const Example  = connection.model('User', exampleSchema);

module.exports = connection;

函数.js

const connection = require("./database");
const Example  = connection.models.Example  ;

推荐阅读