【问题标题】:Connect MongDb and update the values连接 MongoDb 并更新值
【发布时间】:2019-12-01 12:15:32
【问题描述】:

我的目标是更新存储在 MongoDB 中的值,因此我决定使用 mongoose 来查看数据并对其进行编辑,但是;它给了我一个错误。 也许我的方法不对,有没有人已经实现了这种工作。

import * as React from "react";
import * as mongoose from 'mongoose'

export interface State {

}

export default class mongodb extends React.Component<State> {


    constructor(props: {}) {
        super(props);

    }
    private setupDb() : void {
        var mongoDb = 'mongodb://localhost/My_db';
        mongoose.connect(mongoDb);
        console.info("Connected to Mongo.")
        var db = mongoose.connection;
        db.on('error', console.error.bind(console, 'MongoDB Connection error'));
    }

    componentDidMount(){
        this.setupDb()
    }
    render() { 
        return (<div></div>  );
    }
}

错误:

TypeError: mongoose__WEBPACK_IMPORTED_MODULE_1__.connect 不是 功能

【问题讨论】:

  • 不建议直接从 react 连接到你的数据库。前端的用户可以使用代码和数据库链接。安全问题。您应该使用后端来处理来自 react 的调用。
  • 是的,我知道,我只是在测试,首先,需要先从前端更改,然后再更改后端。有什么方法可以编辑吗?以及为什么会出现此错误。

标签: database reactjs mongodb typescript mongoose


【解决方案1】:

您似乎正在尝试从应用程序前端连接到数据库。您需要在后端执行此操作。

确保在您的后端运行npm install mongoose。一旦完成,我认为您的代码将毫无问题地执行。或者,这就是我的做法:

var mongoose = require("mongoose");

const connect = () => {
  mongoose.connect("mongodb://[username]:[password]@1[host]:[port]/[database]");
  //e.g. "mongodb://My_db_user:pw1234@localhost:27017/My_db"
  var db = mongoose.connection;
  db.on("error", console.error.bind(console, "connection error:"));

  db.once("open", function() {
    console.log("Connected to mongo..")
  });
};

然后在您的启动脚本中的某处调用connect()。 如果您不需要任何身份验证来访问您的数据库,并且您在默认端口 27017 上运行,您应该能够使用您的连接 URI (mongodb://localhost/My_db) .

【讨论】:

    【解决方案2】:

    mongoose 发送到前端的包没有连接功能。

    您只能使用后端进行连接。

    看这里 Calling mongoose from react client side

    【讨论】:

      猜你喜欢
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-09
      • 1970-01-01
      • 1970-01-01
      • 2016-05-16
      • 1970-01-01
      相关资源
      最近更新 更多