First time posting on here, FYI.
Below is my "User" model in its own file. I create the schema and assign it. When I go to use this model in my authRoutes file it works fine just as you'd imagine. But when I use an identical import in one of my screen files I receive the "User.findOne is not a function" error message (linked below).
I am using this method to find a user in the database in order to access it's attributes. I have tried using the module.exports way of exporting the model and also trying to use require() as the import statement...neither has fixed my issue...been stuck on this for a while some insight would be great! (Hopefully this was clear, let me know)
"User.findOne is not a function..."
models/User.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
balance: {
type: Number,
default: 100,
}
});
mongoose.model('userSchema', userSchema);
routes/authRoutes.js (Works here)
const mongoose = require('mongoose');
const User = mongoose.model('userSchema');
const express = require('express');
const router = express.Router();
//const User = require('../models/User');
const jwt = require('jsonwebtoken');
router.post('/signup', async (req, res) => {
const {email, password} = req.body;
try {
const user = new User({email, password});
await user.save();
const token = jwt.sign({ userId: user._id}, 'SOME_SECRET_KEY');
res.send({token});
} catch (err) {
return res.status(422).send(err.message);
}
});
router.post("/signin", async (req, res) => {
const {email, password} = req.body;
if (!email || !password) {
return res.status(422).send({error: "Must provide email and password."});
}
const user = await User.findOne({ email });
if (!user) {
return res.status(422).send({ error: "Invalid email or password"});
}
try {
//await user.comparePassword(password);
const token = jwt.sign({userId: user._id}, "SOME_SECRET_KEY");
res.send({token, email});
} catch (err) {
return res.status(422).send({ error: "Invalid email or password"});
}
})
screens/SomeScreen.js (Does NOT work here, error)
import React, {useContext, useState} from 'react'
import {View, StyleSheet, Text, ScrollView, TextInput, Button} from 'react-native';
//import { LinearGradient } from 'expo-linear-gradient';
import colors from '../../constants/colors';
import RecieverCard from '../../components/RecieverCard';
import HistoryCard from '../../components/HistoryCard';
import {Provider, Context} from "../context/AuthContext";
import AsyncStorage from "@react-native-async-storage/async-storage";
const mongoose = require('mongoose');
const User = mongoose.model('userSchema');
const getUserBalance = async (userEmail) => {
let user;
try {
user = await User.findOne(userEmail);
} catch(err) {
console.log(err);
}
return user;
};