Search code examples
node.jsmongoosemongoose-schemabcrypt

why method declared in Mongoose schema wasnt working


So, here's my user schema where i declared hello method onto the Userschema which im using to test

//user.model.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const UserSchema = new Schema({
  username: {
    type: String,
    required: true,
    unique: true,
    trim: true,
    minlength: 3
  },
  password: { type: String, required: true }
});


UserSchema.methods.hello = () => {
  console.log("hello from method");
};

const User = mongoose.model("User", UserSchema);

module.exports = User;

here's routes file

//authroutes.js
const router = require("express").Router();
let User = require("../models/user.model");

router.route("/").get((req, res) => {
  res.send("auth route");
});

router.route("/signup").post((req, res) => {
  const username = req.body.username;
  const password = req.body.password;

  const newUser = new User({
    username,
    password
  });

  newUser
    .save()
    .then(() => res.json(`${username} added`))
    .catch(err => console.log(err));
});

router.route("/login").post(async (req, res) => {
  await User.find({ username: req.body.username }, function(err, user) {
    if (err) throw err;

    //this doesnt work
    user.hello();
    res.end();
  });
});

module.exports = router;

in the login route im calling hello function to test but that doesnt work and throws this error

TypeError: user.hello is not a function


Solution

  • You need to use User.findOne instead of User.find, because find returns an array, but what we need is an instance of the model.

    Also Instance methods shouldn't be declared using ES6 arrow functions. Arrow functions explicitly prevent binding this, so your method will not have access to the document and it will not work.

    So you had better to update method like this:

    UserSchema.methods.hello = function() {
      console.log("hello from method");
    };