TypeError: newUser.find is not a function
if you have body in your request, change the type of request to POST
...after that for use find
don't need to create a instance of model, use find
with Model
router.get("/VerifyEmail", (req, res) => { console.log("Body:", req.body); const data = req.body; User.find({ email: data.email }, function (err, newUser) { if (err) console.log(err); if (newUser) { console.log("ErrorMessage: This email already exists"); } else { console.log("This email is valid"); } }); res.json({ msg: "We received your data!!!", });});
I prefer to use async/await
and don't use Uppercase world for routing check the article: like this
router.post("/verify-email", async (req, res) => { try { let { email } = req.body; let newUser = await User.findOne({ email }); if (newUser) { console.log("ErrorMessage: This email already exists"); } else { console.log("This email is valid"); } } catch (error) { res.json({ msg: "somthing went wrong", }); } res.json({ msg: "We received your data!!!", });});
The proper way to query a Model is like so:
const User = mongoose.model('Users');User.find({<query>}, function (err, newUser) {...
So you need to get the model into a variable (in this case User
) and then run the find
function directly against it, as opposed to running it against an object you instantiate from it. So this is incorrect:
const newUser = new User();newUser.find(...
So assuming all your files and modules are linked up correctly, this should work:
const User = require("../Models/User");User.find({<query>}, function (err, newUser) {...
The problem wasn't actually the mongoose function but I needed to parse the object being sent.
let { email } = JSON.parse(req.body);
Before parsing the object looked like {"email" : "something@gmail.com"}
and after parsing the object looked like {email: 'something@gmail.com'}
I also changed the request from 'get' to 'post' and instead of creating a new instance of the model I simply used User.find() instead of newUser.find()