javascript - 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')
解决方案
试试这样:
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 ;
推荐阅读
- c# - C# 中的非英语复数形式
- angular - SSL证书的角度问题
- flutter - Flutter - DropdownButton onChanged 返回 null
- python - 如何加快代码从字典列表中获取数据
- sql-server - 如何将 OPTION (MAXRECURSION 0) 与 cte insert 一起使用到临时表中
- node.js - 构建单水疗根节点应用程序时未创建 Dist 文件夹
- amazon-web-services - 通过 ASG 启动时为 Terraform 提取 EC2 实例 ID
- java - 如何解决 Java SpringBoot Web 应用程序中的 POM.XML 错误?
- reactjs - 在 react-konva 中添加拖放连接器
- sequence - 雪花:试图使一列默认使用序列中的值