如果您想了解MongodbTypescriptUnhandledPromiseRejectionWarning:TypeError:无法读取Object.connectToDatabase处未定义的属
如果您想了解Mongodb Typescript UnhandledPromiseRejectionWarning:TypeError:无法读取 Object.connectToDatabase 处未定义的属性“conn”[作为默认值]的知识,那么本篇文章将是您的不二之选。同时我们将深入剖析(node:11224) UnhandledPromiseRejectionWarning: TypeError: this.getResolve is not a function、(node:274) UnhandledPromiseRejectionWarning: TypeError: db.all is not a function、(node:7584) UnhandledPromiseRejectionWarning: MongooseTimeoutError: Server selection timed out af...、(React) useDispatch TypeError: Object(...) is not a function handleChange的各个方面,并给出实际的案例分析,希望能帮助到您!
本文目录一览:- Mongodb Typescript UnhandledPromiseRejectionWarning:TypeError:无法读取 Object.connectToDatabase 处未定义的属性“conn”[作为默认值]
- (node:11224) UnhandledPromiseRejectionWarning: TypeError: this.getResolve is not a function
- (node:274) UnhandledPromiseRejectionWarning: TypeError: db.all is not a function
- (node:7584) UnhandledPromiseRejectionWarning: MongooseTimeoutError: Server selection timed out af...
- (React) useDispatch TypeError: Object(...) is not a function handleChange
Mongodb Typescript UnhandledPromiseRejectionWarning:TypeError:无法读取 Object.connectToDatabase 处未定义的属性“conn”[作为默认值]
如何解决Mongodb Typescript UnhandledPromiseRejectionWarning:TypeError:无法读取 Object.connectToDatabase 处未定义的属性“conn”[作为默认值]?
打字稿连接到 mongo 数据库抛出错误,它可以在全局声明 conn 后读取 undefined 的 conn
UnhandledPromiseRejectionWarning: TypeError: 无法读取未定义的属性“conn” 在 Object.connectToDatabase [默认]
import { MongoClient,Db } from "mongodb";
import config from "../config/config";
const { dbname,mongoDBUri } = config;
type MongoConnection = {
client: MongoClient;
db: Db;
};
declare global {
namespace NodeJS {
interface Global {
mongodb: {
conn: MongoConnection | null;
promise: Promise<MongoConnection> | null;
};
}
}
}
let cached = global.mongodb;
async function connectToDatabase() {
if (cached.conn) {
return cached.conn;
}
if (!cached.promise) {
const opts = {
useNewUrlParser: true,useUnifiedTopology: true,};
cached.promise = MongoClient.connect(mongoDBUri as string,opts).then(
(client) => {
return {
client,db: client.db(dbname),};
}
);
}
cached.conn = await cached.promise;
return cached.conn;
}
export default connectToDatabase;
解决方法
您可以使用以下设置
//interfaces/db.interface
export interface dbConfig {
host: string;
port: number;
database: string;
username: string;
password: string;
}
//database.ts
import { dbConfig } from "@interfaces/db.interface";
const { host,port,database,username,password }: dbConfig = config.get("dbConfig");
export const dbConnection = {
url: `mongodb://${username}:${password}@${host}:${port}/${database}?authSource=admin`,options: {
useNewUrlParser: true,useUnifiedTopology: true,useFindAndModify: false,useCreateIndex: true
},};
//app.ts (express app)
import { dbConnection } from "@databases";
constructor(routes: Routes[]) {
this.app = express();
this.port = process.env.PORT || 5000;
this.env = process.env.NODE_ENV || "development";
this.connectToDatabase();
}
private connectToDatabase() {
if (this.env !== "production") {
set("debug",true);
}
connect(dbConnection.url,dbConnection.options)
.catch((error) =>
console.log(`${error}`)
);
}
这里我假设您在 tsconfig.json 文件中设置了路径,以便 @ 可以在导入中使用。
,经过多次尝试,我不得不使用 NextJs MongoDB 连接模式并将其转换为打字稿,并且效果很好
import config from "./../config/config";
import { MongoClient,Db } from "mongodb";
const { dbName,mongoDBUri } = config;
if (!mongoDBUri) {
throw new Error(
"Define the mongoDBUri environment variable inside .env"
);
}
if (!dbName) {
throw new Error(
"Define the dbName environment variable inside .env"
);
}
type MongoConnection = {
client: MongoClient;
db: Db;
};
declare global {
namespace NodeJS {
interface Global {
mongodb: {
conn: MongoConnection | null;
promise: Promise<MongoConnection> | null;
};
}
}
}
let cached = global.mongodb;
if (!cached) {
cached = global.mongodb = { conn: null,promise: null };
}
export default async function connectToDatabase() {
if (cached.conn) {
return cached.conn;
}
if (!cached.promise) {
console.log("Establishing new database connection");
const opts = {
useNewUrlParser: true,};
cached.promise = MongoClient.connect(mongoDBUri as string,opts).then(
(client) => {
return {
client,db: client.db(dbName),};
}
);
}
cached.conn = await cached.promise;
return cached.conn;
}
(node:11224) UnhandledPromiseRejectionWarning: TypeError: this.getResolve is not a function
来自/感谢:https://blog.csdn.net/qq_43379916/article/details/109190506
版本过高错误
比如我的webpack是3.6.0版本
而我的css-loader是5.0.0
这里就会出现这个错误
解决办法:
1,手动设置,然后采用npm install 重新下载
2,卸载重装
npm uninstall css-loader //卸载 npm install css-loader@3.0.0 --save-dev //指定版本重装
(node:274) UnhandledPromiseRejectionWarning: TypeError: db.all is not a function
如何解决(node:274) UnhandledPromiseRejectionWarning: TypeError: db.all is not a function?
这是我第一次在这里提问,所以请您尽快回答我,谢谢!无论如何,我正在使用 discord.js API 制作一个不和谐的机器人,但我遇到了一个问题。
代码:
if(message.content === PREFIX +"leaderboard"||"lb") {
let money = db.all().filter(data => data.ID.startsWith(`money_`)).sort((a,b) => b.data - a.data);
if (!money.length) {
let noEmbed = new discord.MessageEmbed()
.setAuthor(message.member.displayName,message.author.displayAvatarURL())
.setColor("GREEN")
.setFooter("nothing To See Here Yet!")
return message.channel.send(noEmbed)
};
错误:
UnhandledPromiseRejectionWarning: TypeError: db.all is not a function
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
(node:7584) UnhandledPromiseRejectionWarning: MongooseTimeoutError: Server selection timed out af...
记录一次学习node.js犯的低级错误
这里遇到一个这样的问题
express连接mongoose时报错(node:7584) UnhandledPromiseRejectionWarning: MongooseTimeoutError: Server selection timed out after 30000 ms
连接数据库的代码
1 const mongoose=require(''mongoose'')
2 mongoose.connect(''mongodb://localhost:27017/express1'',{
3 useNewUrlParser: true,
4 useUnifiedTopology: true
5 })
6
7
8 const UserSchema=new mongoose.Schema({
9 username:{type:String},
10 password:{type:String}
11 })
12 const User=mongoose.model(''User'',UserSchema)
13 module.exports = {
14 User
15 }
按照网上教程说不需用启动数据库直接可以连接,可是怎么也连接不上,一直报超时错误,网上查了一大堆的资料,有的说需要什么超级管理员权限,折腾了好久也没搞出来,而且网上这类似的问题很少,看来是没啥人遇到这样的问题,那估计就是我自己哪儿没写对吧,反复排查之后觉得可能还是需要本地启动mongod,然后尝试cmd里面启动mongod,再从新启动项目,终于成功了
(React) useDispatch TypeError: Object(...) is not a function handleChange
如何解决(React) useDispatch TypeError: Object(...) is not a function handleChange?
我正在做一个简单的 React 应用程序,其中任何用户在输入文本中引入一个文本,它会自动更新商店中的状态。 这是 React 的非常简单的实践,但我对这个错误感到非常挣扎和沮丧,因为我尝试了所有方法,但仍然遇到同样的问题。
我正在使用“react-redux”和“@reduxjs/toolkit”依赖项。我尝试了所有方法,检查并比较了类似问题的类似示例和解决方案,我从头开始重新制作了该应用程序,以确保不同版本的依赖项没有任何问题,并且我尝试使我的代码非常简单它有效,但无效。
我希望你们中的任何人都可以给我建议或解决方案。 谢谢!!
错误
TypeError: Object(...) is not a function
handleChange
C:/Users/Ruben/Desktop/Projects/React/reddit2/reddit/src/features/search/SearchBar.js:14
11 |
12 |
13 | const handleChange = (e) => {
> 14 | dispatch(setSearchTerm(e.target.value))
| ^ 15 | }
16 |
17 |
View compiled
▶ 19 stack frames were collapsed.
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error. Click the ''X'' or hit ESC to dismiss this message.
这些是文件:
SearchBar 组件
import React from "react";
import {usedispatch,useSelector} from "react-redux";
import {setSearchTerm,selectSearchTerm} from "../search/searchSlice";
export const SearchBar = () => {
const dispatch = usedispatch();
const term = useSelector(selectSearchTerm);
const handleChange = (e) => {
dispatch(setSearchTerm(e.target.value))
}
return(
<div>
<input
id="search"
type="text"
value={term}
onChange={handleChange}
placeholder="Introduce your Topic"
/>
</div>
);
};
searchSlice
import {createSlice} from "@reduxjs/toolkit";
export const searchSlice = createSlice({
name: ''search'',initialState: '''',reducer: {
setSearchTerm: (state,action) => {state.search = action.payload},}
});
export const {setSearchTerm} = searchSlice.actions;
export const selectSearchTerm = (state) => state.search;
export default searchSlice.reducer;
商店
import {configureStore} from "@reduxjs/toolkit";
import searchReducer from "../features/search/searchSlice";
export default configureStore({
reducer: {
search: searchReducer,},});
索引
import React from ''react'';
import ReactDOM from ''react-dom'';
import { Provider } from "react-redux";
import ''./index.css'';
import App from ''../src/App/App'';
import reportWebVitals from ''./reportWebVitals'';
import store from "../src/App/store";
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,document.getElementById(''root'')
);
Package.json
{
"name": "reddit","version": "0.1.0","private": true,"dependencies": {
"@reduxjs/toolkit": "^1.5.1","@testing-library/jest-dom": "^5.13.0","@testing-library/react": "^11.2.7","@testing-library/user-event": "^12.8.3","react": "^17.0.2","react-dom": "^17.0.2","react-redux": "^7.2.4","react-scripts": "4.0.3","web-vitals": "^1.1.2"
},
解决方法
问题
- 您在
createSlice
中有一个拼写错误,正确的键是reducers
,带有“s”,而不是reducer
。这导致切片操作实际上未定义。 - 您的状态不太正确。它不是一个可起草的对象。
解决方案
更正reducer key并提供正确的状态。
export const searchSlice = createSlice({
name: "search",initialState: { search: "" },// <-- object state
reducers: {
setSearchTerm: (state,action) => {
state.search = action.payload; // <-- update property
}
}
});
export const { setSearchTerm } = searchSlice.actions;
export const selectSearchTerm = (state) => state.search.search; // <-- select property
export default searchSlice.reducer;
今天关于Mongodb Typescript UnhandledPromiseRejectionWarning:TypeError:无法读取 Object.connectToDatabase 处未定义的属性“conn”[作为默认值]的讲解已经结束,谢谢您的阅读,如果想了解更多关于(node:11224) UnhandledPromiseRejectionWarning: TypeError: this.getResolve is not a function、(node:274) UnhandledPromiseRejectionWarning: TypeError: db.all is not a function、(node:7584) UnhandledPromiseRejectionWarning: MongooseTimeoutError: Server selection timed out af...、(React) useDispatch TypeError: Object(...) is not a function handleChange的相关知识,请在本站搜索。
本文标签: