I have been trying to access my method that I have declared in User Schema first but when I try to get access to my addPresent method in the controllers where I already have require User Schema and have created new User but again i am facing the same error again. I am fairly new to mongoose and express, and I'm pretty sure I have my files set up currently so I don't know what could be causing this issue. As a last attempt, I tried switching to arrow functions , but that didn't work either.
`Schema Section `
const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const dotenv = require("dotenv");
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
rollNo: {
type: Number,
required: true,
},
date: {
type: Date,
// required: true,
},
department: {
type: String,
required: true,
},
section: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
confirmPassword: {
type: String,
required: true,
},
tokens: [
{
token: {
type: String,
required: true,
},
},
],
presents: [
{
date: {
type: Date,
},
presentCount: {
type: String,
},
},
],
leaves: [
{
date: {
type: Date,
},
reason: {
type: String,
},
leaveCount: {
type: Number,
},
},
],
});
`Creating Methods`
userSchema.methods.addPresent = async function (count) {
try {
this.presents = this.presents.concat({
date: Date.now(),
presentCount: count,
});
await this.save();
return this.presents;
} catch (error) {
console.log(error);
}
};
const user = mongoose.model("user", userSchema);
module.exports = user;
`In controllers where i'm accessing my method`
const User = require("../models/userSchema");
exports.presentUser = async (req, res) => {
const user = req.userRoot;
const userId = req.userRoot._id;
console.log(userId);
count = count + 1;
if (user) {
const present = User.findOne({ _id: userId });
`Here is the main problem where i am accessing the addPresent method`
if (present) {
const addAttendance = await present.addPresent();
await present.save();
}
}
};