I've run into an issue that I can't seem to fix, been playing around with mongoose for about a week now, and I've done almost this exact same thing in previous personal projects, but I can't seem to figure out why it's not working this time around..I have a schema created on a user model in mongoose and I'm trying to add a method to the statics object called findByCredentials, which will query the database to find a matching email/password in a document. My findByCredentials method is not detected in my routes file. I can see all the default mongodb methods are detected, so atleast that is working properly. I just can't for the life of me figure out WHY my methods are not detected.I've tested this with with both pre() middleware and placing instance methods on the methods object, neither of those are detected either. Really could use some help here!User Model:const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: { type: String, required: true, trim: true }, email: { type: String, required: true, trim: true }, password: { type: String, required: true, trim: true } }); userSchema.statics.findByCredentials = function(email, password) { User.findOne({ email }) .then(user => { return user; }) .catch(err => { return 'Unable to login'; }); } const User = mongoose.model('User', userSchema); module.exports = User; Routes File:const express = require('express'); const router = new express.Router(); require('../db/mongoose'); const User = require('../models/user'); router.get('/', (req, res) => { User.find({}) .then(users => { res.send(users); }) .catch(err => { res.status(500).send(); }); }); router.post('/', (req, res) => { const user = new User(req.body); user.save() .then(savedUser => { res.send(savedUser); }) .catch(err => { res.status(500).send(err); }); }); router.post('/login', (req, res) => { //trying to use findByCredentials here }); module.exports = router;
Submitted January 18, 2020 at 04:37PM by mightybjorn
No comments:
Post a Comment