1

My goal is to update values that stored in MongoDB, therefore I have decided to use mongoose to see data and edit them, However; it gives me an error. Maybe I am in the wrong way, does anybody has already implemented this kind work.

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>  );
    }
}

The error:

TypeError: mongoose__WEBPACK_IMPORTED_MODULE_1__.connect is not a function

2
  • 2
    It is not advisable to connect directly to your database from react. The code and the link to your database will be available to the user in the front end. Security issue. You should be using a backend to handle calls from react. Commented Jul 23, 2019 at 13:03
  • Yes I know, I am just testing, first of all, and need to change from the front side then backend. Is there any way to edit? and why this error comes. Commented Jul 23, 2019 at 13:14

2 Answers 2

1

It looks like you're trying to connect to the database from the application frontend. You need to do this in the backend.

In your backend, make sure you run npm install mongoose. Once that is done, I think your code will execute without any problems. Alternatively, this is how I've done it:

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..")
  });
};

Followed by a call to connect() somewhere in your startup script. If you don't require any authentication for accessing your database, and you're running on the default port of 27017, you should be able to use your connection URI (mongodb://localhost/My_db).

Sign up to request clarification or add additional context in comments.

Comments

1

package shipped to frontend by mongoose does not have the connect function.

you can only connect using a backend.

see here Calling mongoose from react client side

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.