简体   繁体   中英

How to query a mongoose returned value

Am trying to query a value that's returned from mongoose callback function, but all I get is TypeError: #<Object> is not a function . I know it might not be easy to do that, but with the way am querying the db I need to dive more deep from the returned results, without really having to call up the User model again. I don't know if there's a way to go around that.

 User.findOne({_id: req.user.id}, function(err,user){
        if(err){
            console.log(err);
        } else {
            if(user.plan == 'hit'){
                User.find({plan: 'hit', verified: 'yes'}).lean().exec(function(error,*suc*){
                    if(suc.length < 1){
                        console.log(error);
                        console.log('no user')
                    } else {
                        console.log(suc)

                        **Error throws up right below here**

                        *suc*.find({admintit: 'admin', adminLimit: 200, admincycle: 0}, function(errok,hungad){
                            if(errok){
                                console.log(err)
                            } else {
                                if(hungad.length < 1){
                                    console.log('no hung admin');
                                } else {
                                    console.log(hungad)
                                }
                            }
                        })
                    }
                })
            }
        }
    })

Really trying to query the suc callback result, but all I get is an error, I have tried converting it to an object Object.assign({}, suc) but it still returns same error, that it's not a function.

suc is going to be an array of results where the error occurs, meaning if you call find you will get Array.prototype.find and not mongoose find.

If you actually want to call Array.prototype.find assuming the object looks like:

const suc = [{admintit: 'admin', adminLimit: 200, admincycle: 0}, ...]

You should change it to:

const admin = suc.find(result => result.admintit === 'admin' && result.adminLimit === 200 && result.admincycle === 0)
if (admin) {
    console.log(admin)
} else {
    console.log('no hung admin');
}

If you want to find all you can change find to filter :

const admins = suc.filter(result => result.admintit === 'admin' && result.adminLimit === 200 && result.admincycle === 0)
if (admins.length > 0) {
    console.log(admins)
} else {
    console.log('no hung admin');
}

If you were looking to call find for mongoose then you will have to define it on the schema

User.method('find', function () {
    // do something
});

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