Search code examples
node.jsmongodbreact-nativemongoosereact-native-web

Unhandled Rejection (TypeError): mongoose.connect is not a function


I've tried a bunch of different changes, but nothing seems to be working. I've tried switching to an import statement. I've tried putting the code in App.js. I've tried using the mongodb library instead of mongoose. I've followed a dozen tutorials on connecting to mongodb. For some reason, the connect statement keeps throwing this error. What am I missing?

const mongoose = require('mongoose');

export async function post({username, password}) {
  const data = {username, password};
  const uri =
    'mongodb+srv://[username removed]:[password removed]@[project name removed].krcm7.mongodb.net/database?retryWrites=true&w=majority';
  mongoose
    .connect(uri, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })
    .then((result) => console.log('connected to db'))
    .catch((err) => console.log(err));

  return;
}

To add context, this is how the function is being called.

function submitForm(username, password) {
  post(username, password).then(() => {
    console.log('post function ran');
  });
}

Solution

  • I found the problem. Mongodb and mongoose are designed to work specifically in node.js and won't work in a browser environment.