Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
Using a Mongoose Schema Function Inside Of An Exported Mongoose Model

I have been working on an authentication system lately that is supposed to either create a new user if no user with a given ID exists OR loads in a user with an existing ID. I also already figured out that you can return whether or not a user exists with in ID by using

User.count({_id: id}, function (err, count){ 
    if(count > 0){
      // User exists, continue with loading data
    } else {
      // User does not exist, create one
    }
  });

with User being an exported Mongoose Model mongoose.model('User', UserSchema);

If I created a function existsWithId(id) in my app.js now, it would work perfectly fine (judging by the fact that the previously mentioned code works perfectly fine), but I want to move this function to my user.js Model (which contains the Mongoose / MongoDB Code) instead so that I have it only for that specific model. Whenever I try to do that by using

UserSchema.statics.existsWithId = function(id) {
  this.count({_id: id}, function (err, count){ 
    return count > 0;
  }); 
}

or similar methods, though, it will either just return undefined or an error once I run it inside of my app.js.

NOTE: I'm sorry if this is a kind of simple or even foolish question, but I am pretty new considering DB management with Mongoose and while I do have SOME experience with JS, I am not exactly a professional at it.

If any of you need additional code provided to answer the question, feel free to ask me and I will do so. Also, I can't +rep answers yet, but I always appreciate 'em :)

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Your existsWithId method returns a value asynchronously so you can give a callback to it to get the result back like this :

UserSchema.statics.existsWithId = function(id, cb) {
    this.count({ _id: id }, function(err, count) {
        cb(err, count > 0);
    });
}

User.existsWithId("5882c3be5aad09028d4d8b46", function(err, res) {
    console.log(res);
});
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!