Reputation: 584
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
Upvotes: 1
Views: 76
Reputation: 115
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
Upvotes: 1
Reputation: 372
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).
Upvotes: 1