mongoose static method undefined [duplicate]Mongoose 'static' methods vs. 'instance' methodsTypescript mongoose static model method “Property does not exist on type”Detecting an undefined object propertyHow to check empty/undefined/null string in JavaScript?How to determine if variable is 'undefined' or 'null'?How to check for “undefined” in JavaScript?Is there a standard function to check for null, undefined, or blank variables in JavaScript?NodeJs, Mocha and MongooseNodeJS Mongoose Schema 'save' function error handling?Packing data with mongooseI got an empty array in sub document array saving using mongoose ( MEAN stack)Mongoose duplicate queries

Problem with estimating a sequence with intuition

How can I finally understand the confusing modal verb "мочь"?

What do you call a painting painted on a wall?

Summer '19 Sandbox error: String index out of range: 0: Source

How did the Force make Luke hard to hit in the Battle of Yavin?

Ab major 9th chord in Bach

Find the area of the smallest rectangle to contain squares of sizes up to n

Playing Doublets with the Primes

Changing stroke width vertically but not horizontally in Inkscape

What is monoid homomorphism exactly?

How important are good looking people in a novel/story?

How to replace space with '+' symbol in a triangular array?

Installing Debian 10, upgrade to stable later?

What's the 2-minute timer on mobile Deutsche Bahn tickets?

Is throwing dice a stochastic or a deterministic process?

Two denim hijabs

How did the Apollo guidance computer handle parity bit errors?

What does のそ mean on this picture?

Is there a reason why Turkey took the Balkan territories of the Ottoman Empire, instead of Greece or another of the Balkan states?

Efficient deletion of specific list entries

HSA - Continue to Invest?

What are these silver "sporks" for?

Has the United States ever had a non-Christian President?

As a GM, is it bad form to ask for a moment to think when improvising?



mongoose static method undefined [duplicate]


Mongoose 'static' methods vs. 'instance' methodsTypescript mongoose static model method “Property does not exist on type”Detecting an undefined object propertyHow to check empty/undefined/null string in JavaScript?How to determine if variable is 'undefined' or 'null'?How to check for “undefined” in JavaScript?Is there a standard function to check for null, undefined, or blank variables in JavaScript?NodeJs, Mocha and MongooseNodeJS Mongoose Schema 'save' function error handling?Packing data with mongooseI got an empty array in sub document array saving using mongoose ( MEAN stack)Mongoose duplicate queries






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0
















This question already has an answer here:



  • Mongoose 'static' methods vs. 'instance' methods

    2 answers



  • Typescript mongoose static model method “Property does not exist on type”

    4 answers



I am trying to authenticate using jwt but for some reason the static method named isCorrectPassword is always undefined in the user instance.



If I console.log user then I see the has, _id etc so the db connection and find works but not the static method. I am not sure what is wrong here.



// User schema
const Schema = require("mongoose")
const bcrypt = require("bcrypt")

const UserSchema = new Schema(
email: type: String, required: true, unique: true ,
password: type: String, required: true
)

UserSchema.statics.isCorrectPassword = function(password, callback)
console.log(callback)
bcrypt.compare(password, this.password).then(function(err, same)
if (err)
callback(err)
else
callback(err, same)

)


module.exports = UserSchema


// User model
const mongoose = require("mongoose")
const bcrypt = require("bcrypt")
const UserSchema = require("../schemas/user")

const saltRounds = 10

UserSchema.pre("save", function(next) this.isModified("password"))
// Saving reference to this because of changing scopes
const document = this
bcrypt.hash(document.password, saltRounds, function(err, hashedPassword)
if (err)
next(err)
else
document.password = hashedPassword
next()

)
else
next()

)

module.exports = mongoose.model("User", UserSchema)


const jwt = require("jsonwebtoken")
const db = require("../db")

const secret = process.env.REACT_APP_AUTH_SECRET

function userAuth(router)
router.post("/authenticate", async (req, res) =>
const email, password = req.body

const Users = db.collection("users")

Users.findOne( email , function(err, user)
if (err)
console.error(err)
res.status(500).json(
error: "Internal error please try again"
)
else if (!user)
res.status(401).json(
error: "Incorrect email or password"
)
else
user.isCorrectPassword(password, function(err, same)
if (err)
res.status(500).json(
error: "Internal error please try again"
)
else if (!same)
res.status(401).json(
error: "Incorrect email or password"
)
else
// Issue token
const payload = email
const token = jwt.sign(payload, secret,
expiresIn: "1h"
)
res.cookie("token", token, httpOnly: true ).sendStatus(200)

)

)
)


module.exports = userAuth









share|improve this question















marked as duplicate by Neil Lunn javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 23 at 4:52


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


















  • "... is always undefined in the user instance." - Which is completely correct since static methods are for the Model and NOT the instance. If you want to work with "instance data" from a new or a find()("like") result then you want methods instead.

    – Neil Lunn
    Mar 23 at 4:52











  • replacing .statics with .methods returns the same result, undefined.

    – AspiringCanadian
    Mar 23 at 4:57






  • 1





    Not if you take more than 5 minutes to literally just replace statics with method in your code. Read the responses, and look at the documentation in order to understand the differences of when you use one over the other. If everything was answered by "search and replace" then that would be just peachy! But in the real world you actually need to stop and learn things when something goes wrong. Now you know where to look. Take some time, since you probably won't absorb this in just a few minutes But it's still the same answer.

    – Neil Lunn
    Mar 23 at 5:01


















0
















This question already has an answer here:



  • Mongoose 'static' methods vs. 'instance' methods

    2 answers



  • Typescript mongoose static model method “Property does not exist on type”

    4 answers



I am trying to authenticate using jwt but for some reason the static method named isCorrectPassword is always undefined in the user instance.



If I console.log user then I see the has, _id etc so the db connection and find works but not the static method. I am not sure what is wrong here.



// User schema
const Schema = require("mongoose")
const bcrypt = require("bcrypt")

const UserSchema = new Schema(
email: type: String, required: true, unique: true ,
password: type: String, required: true
)

UserSchema.statics.isCorrectPassword = function(password, callback)
console.log(callback)
bcrypt.compare(password, this.password).then(function(err, same)
if (err)
callback(err)
else
callback(err, same)

)


module.exports = UserSchema


// User model
const mongoose = require("mongoose")
const bcrypt = require("bcrypt")
const UserSchema = require("../schemas/user")

const saltRounds = 10

UserSchema.pre("save", function(next) this.isModified("password"))
// Saving reference to this because of changing scopes
const document = this
bcrypt.hash(document.password, saltRounds, function(err, hashedPassword)
if (err)
next(err)
else
document.password = hashedPassword
next()

)
else
next()

)

module.exports = mongoose.model("User", UserSchema)


const jwt = require("jsonwebtoken")
const db = require("../db")

const secret = process.env.REACT_APP_AUTH_SECRET

function userAuth(router)
router.post("/authenticate", async (req, res) =>
const email, password = req.body

const Users = db.collection("users")

Users.findOne( email , function(err, user)
if (err)
console.error(err)
res.status(500).json(
error: "Internal error please try again"
)
else if (!user)
res.status(401).json(
error: "Incorrect email or password"
)
else
user.isCorrectPassword(password, function(err, same)
if (err)
res.status(500).json(
error: "Internal error please try again"
)
else if (!same)
res.status(401).json(
error: "Incorrect email or password"
)
else
// Issue token
const payload = email
const token = jwt.sign(payload, secret,
expiresIn: "1h"
)
res.cookie("token", token, httpOnly: true ).sendStatus(200)

)

)
)


module.exports = userAuth









share|improve this question















marked as duplicate by Neil Lunn javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 23 at 4:52


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


















  • "... is always undefined in the user instance." - Which is completely correct since static methods are for the Model and NOT the instance. If you want to work with "instance data" from a new or a find()("like") result then you want methods instead.

    – Neil Lunn
    Mar 23 at 4:52











  • replacing .statics with .methods returns the same result, undefined.

    – AspiringCanadian
    Mar 23 at 4:57






  • 1





    Not if you take more than 5 minutes to literally just replace statics with method in your code. Read the responses, and look at the documentation in order to understand the differences of when you use one over the other. If everything was answered by "search and replace" then that would be just peachy! But in the real world you actually need to stop and learn things when something goes wrong. Now you know where to look. Take some time, since you probably won't absorb this in just a few minutes But it's still the same answer.

    – Neil Lunn
    Mar 23 at 5:01














0












0








0









This question already has an answer here:



  • Mongoose 'static' methods vs. 'instance' methods

    2 answers



  • Typescript mongoose static model method “Property does not exist on type”

    4 answers



I am trying to authenticate using jwt but for some reason the static method named isCorrectPassword is always undefined in the user instance.



If I console.log user then I see the has, _id etc so the db connection and find works but not the static method. I am not sure what is wrong here.



// User schema
const Schema = require("mongoose")
const bcrypt = require("bcrypt")

const UserSchema = new Schema(
email: type: String, required: true, unique: true ,
password: type: String, required: true
)

UserSchema.statics.isCorrectPassword = function(password, callback)
console.log(callback)
bcrypt.compare(password, this.password).then(function(err, same)
if (err)
callback(err)
else
callback(err, same)

)


module.exports = UserSchema


// User model
const mongoose = require("mongoose")
const bcrypt = require("bcrypt")
const UserSchema = require("../schemas/user")

const saltRounds = 10

UserSchema.pre("save", function(next) this.isModified("password"))
// Saving reference to this because of changing scopes
const document = this
bcrypt.hash(document.password, saltRounds, function(err, hashedPassword)
if (err)
next(err)
else
document.password = hashedPassword
next()

)
else
next()

)

module.exports = mongoose.model("User", UserSchema)


const jwt = require("jsonwebtoken")
const db = require("../db")

const secret = process.env.REACT_APP_AUTH_SECRET

function userAuth(router)
router.post("/authenticate", async (req, res) =>
const email, password = req.body

const Users = db.collection("users")

Users.findOne( email , function(err, user)
if (err)
console.error(err)
res.status(500).json(
error: "Internal error please try again"
)
else if (!user)
res.status(401).json(
error: "Incorrect email or password"
)
else
user.isCorrectPassword(password, function(err, same)
if (err)
res.status(500).json(
error: "Internal error please try again"
)
else if (!same)
res.status(401).json(
error: "Incorrect email or password"
)
else
// Issue token
const payload = email
const token = jwt.sign(payload, secret,
expiresIn: "1h"
)
res.cookie("token", token, httpOnly: true ).sendStatus(200)

)

)
)


module.exports = userAuth









share|improve this question

















This question already has an answer here:



  • Mongoose 'static' methods vs. 'instance' methods

    2 answers



  • Typescript mongoose static model method “Property does not exist on type”

    4 answers



I am trying to authenticate using jwt but for some reason the static method named isCorrectPassword is always undefined in the user instance.



If I console.log user then I see the has, _id etc so the db connection and find works but not the static method. I am not sure what is wrong here.



// User schema
const Schema = require("mongoose")
const bcrypt = require("bcrypt")

const UserSchema = new Schema(
email: type: String, required: true, unique: true ,
password: type: String, required: true
)

UserSchema.statics.isCorrectPassword = function(password, callback)
console.log(callback)
bcrypt.compare(password, this.password).then(function(err, same)
if (err)
callback(err)
else
callback(err, same)

)


module.exports = UserSchema


// User model
const mongoose = require("mongoose")
const bcrypt = require("bcrypt")
const UserSchema = require("../schemas/user")

const saltRounds = 10

UserSchema.pre("save", function(next) this.isModified("password"))
// Saving reference to this because of changing scopes
const document = this
bcrypt.hash(document.password, saltRounds, function(err, hashedPassword)
if (err)
next(err)
else
document.password = hashedPassword
next()

)
else
next()

)

module.exports = mongoose.model("User", UserSchema)


const jwt = require("jsonwebtoken")
const db = require("../db")

const secret = process.env.REACT_APP_AUTH_SECRET

function userAuth(router)
router.post("/authenticate", async (req, res) =>
const email, password = req.body

const Users = db.collection("users")

Users.findOne( email , function(err, user)
if (err)
console.error(err)
res.status(500).json(
error: "Internal error please try again"
)
else if (!user)
res.status(401).json(
error: "Incorrect email or password"
)
else
user.isCorrectPassword(password, function(err, same)
if (err)
res.status(500).json(
error: "Internal error please try again"
)
else if (!same)
res.status(401).json(
error: "Incorrect email or password"
)
else
// Issue token
const payload = email
const token = jwt.sign(payload, secret,
expiresIn: "1h"
)
res.cookie("token", token, httpOnly: true ).sendStatus(200)

)

)
)


module.exports = userAuth




This question already has an answer here:



  • Mongoose 'static' methods vs. 'instance' methods

    2 answers



  • Typescript mongoose static model method “Property does not exist on type”

    4 answers







javascript node.js mongoose






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 23 at 4:54









Neil Lunn

102k23183189




102k23183189










asked Mar 23 at 4:43









AspiringCanadianAspiringCanadian

83621330




83621330




marked as duplicate by Neil Lunn javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 23 at 4:52


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by Neil Lunn javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 23 at 4:52


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • "... is always undefined in the user instance." - Which is completely correct since static methods are for the Model and NOT the instance. If you want to work with "instance data" from a new or a find()("like") result then you want methods instead.

    – Neil Lunn
    Mar 23 at 4:52











  • replacing .statics with .methods returns the same result, undefined.

    – AspiringCanadian
    Mar 23 at 4:57






  • 1





    Not if you take more than 5 minutes to literally just replace statics with method in your code. Read the responses, and look at the documentation in order to understand the differences of when you use one over the other. If everything was answered by "search and replace" then that would be just peachy! But in the real world you actually need to stop and learn things when something goes wrong. Now you know where to look. Take some time, since you probably won't absorb this in just a few minutes But it's still the same answer.

    – Neil Lunn
    Mar 23 at 5:01


















  • "... is always undefined in the user instance." - Which is completely correct since static methods are for the Model and NOT the instance. If you want to work with "instance data" from a new or a find()("like") result then you want methods instead.

    – Neil Lunn
    Mar 23 at 4:52











  • replacing .statics with .methods returns the same result, undefined.

    – AspiringCanadian
    Mar 23 at 4:57






  • 1





    Not if you take more than 5 minutes to literally just replace statics with method in your code. Read the responses, and look at the documentation in order to understand the differences of when you use one over the other. If everything was answered by "search and replace" then that would be just peachy! But in the real world you actually need to stop and learn things when something goes wrong. Now you know where to look. Take some time, since you probably won't absorb this in just a few minutes But it's still the same answer.

    – Neil Lunn
    Mar 23 at 5:01

















"... is always undefined in the user instance." - Which is completely correct since static methods are for the Model and NOT the instance. If you want to work with "instance data" from a new or a find()("like") result then you want methods instead.

– Neil Lunn
Mar 23 at 4:52





"... is always undefined in the user instance." - Which is completely correct since static methods are for the Model and NOT the instance. If you want to work with "instance data" from a new or a find()("like") result then you want methods instead.

– Neil Lunn
Mar 23 at 4:52













replacing .statics with .methods returns the same result, undefined.

– AspiringCanadian
Mar 23 at 4:57





replacing .statics with .methods returns the same result, undefined.

– AspiringCanadian
Mar 23 at 4:57




1




1





Not if you take more than 5 minutes to literally just replace statics with method in your code. Read the responses, and look at the documentation in order to understand the differences of when you use one over the other. If everything was answered by "search and replace" then that would be just peachy! But in the real world you actually need to stop and learn things when something goes wrong. Now you know where to look. Take some time, since you probably won't absorb this in just a few minutes But it's still the same answer.

– Neil Lunn
Mar 23 at 5:01






Not if you take more than 5 minutes to literally just replace statics with method in your code. Read the responses, and look at the documentation in order to understand the differences of when you use one over the other. If everything was answered by "search and replace" then that would be just peachy! But in the real world you actually need to stop and learn things when something goes wrong. Now you know where to look. Take some time, since you probably won't absorb this in just a few minutes But it's still the same answer.

– Neil Lunn
Mar 23 at 5:01













0






active

oldest

votes

















0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes

Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현