简体   繁体   中英

Mongoose not returning, but mongo shell is

I'm using mongoose on my node app, and I want to get a seller by its email:

getSellerByEmail : function(email,next){
        var Seller = mongoose.model('Seller');
        console.log(inspect(email));
        Seller.findOne({'email' : new RegExp(email, 'i')}, function(seller){

            next(seller);
        });
    }

When I try to login, mongoose does not return the new user. But when I try to create another user with the same email, the server executes this function correctly and it returns the new user.

Also tried with {'email' : email} and It returns null , but when I do this query on mongo shell, it returns correctly.

db.sellers.findOne({email : 'email@email.email'});
{
   "_id" : ObjectId("54b94759b042bdbf19cb7b97"),
   "name" : "Nome da Empresa",
   "cnpj" : "123123123",
   "email" : "email@email.email",
   "password" : "$2a$08$6UvW8Bux3CwUMok8ac12Sehbd.xCHnVUI51ZwhtGKBjkSa6/MrqUu",
   "__v" : 0
}

I'm new to mongodb + mongoose, so I know it's a dumb question, but I just can't realize what is wrong... I've also created a findSellerById() function, and it works perfectly.

EDIT 1:

Using Mongoose debug, here's what it's printed:

Mongoose: sellers.findOne({ email: 'email@email.email' }) { fields: undefined }
Mongoose: sellers.findOne({}) { fields: undefined }

As you can see, also tried with no parameters, no success...

I had the same problem, maybe you could try this:

Seller.find({email: seller.email}, function(err, seller){
    console.log(seller);
});

This solved mine, hope it will solve yours too !

The callback function passed into findOne takes two parameters (error and doc), so you're treating seller as the error parameter instead of the doc parameter.

So your function should look like this instead:

getSellerByEmail : function(email,next){
    var Seller = mongoose.model('Seller');
    console.log(inspect(email));
    Seller.findOne({'email' : new RegExp(email, 'i')}, function(err, seller){
        next(seller);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM