Max H.
Max H.

Reputation: 45

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 :)

Upvotes: 3

Views: 1426

Answers (1)

Bertrand Martel
Bertrand Martel

Reputation: 45352

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);
});

Upvotes: 1

Related Questions