I can't test if mongoose returned a document.

2019-09-16 01:04发布

问题:

Why doesn't the below code hit the if condition?

The console.log("returnAnonModel -----", returnAnonModel, "typeof : ", typeof returnAnonModel) returns

returnAnonModel ----- [ { _id: 57d21d2deaa0c4c8297311a6,
    __v: 0,
    usefulness: [],
    reviews: [] } ] typeof :  object

The code:

    Anon.find({_id : app.locals.user._id})
    .then(function( returnAnonModel){
        console.log("returnAnonModel -----", returnAnonModel, "typeof : ", typeof returnAnonModel)
        console.log("Object.keys(returnAnonModel).length", Object.keys(returnAnonModel.toObject()).length)
        console.log("returnAnonModel.toObject()---", returnAnonModel.toObject())
        if(returnAnonModel){
            console.log("*************Anon user found*********************");
        }else{
            console.log("Anon user NOT found--")
        }

EDIT : I just tried if(returnAnonModel.length){ and still the logs in the if or else don't get displayed

EDIT2 : I changed it to below and now it works. why? Is it because I have the returnAnonModel it the console 2 times I know this time I use findOne instead of find. What is the main difference?

    Anon.findOne({_id : app.locals.user._id})
    .then(function( returnAnonModel){
        console.log("*******", returnAnonModel ,"***********88")
        // console.log("returnAnonModel -----", returnAnonModel, "typeof : ", typeof returnAnonModel)
        // console.log("Object.keys(returnAnonModel).length", Object.keys(returnAnonModel.toObject()).length)
        // console.log("returnAnonModel.toObject()---", returnAnonModel.toObject())

        if(returnAnonModel){
            console.log("*************Anon user found*********************");
        }else{
            console.log("*************Anon user NOT found*************")
        }