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

How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?