不知道为什么if条件不检测操作数是否为对象

Don't know why the if condition is not detecting if the operand is an object or not

本文关键字:操作数 是否 对象 检测 为什么 if 条件 不知道      更新时间:2023-09-26

在这个问题的底部,我有代码:console.log("returnAnonModel -----", returnAnonModel, "typeof : ", typeof returnAnonModel),它记录returnAnonModel是一个对象。我不明白为什么if else条件没有被满足。

首先让我告诉你它记录了什么:

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

这个问题很直接。你看到了这个物体,但显然Object.keys(returnAnonModel).length > 0在if条件下不为真。这个物体的长度不应该是4吗?我不能看看里面的控制台吗?console.log("***********Anon USER SEARCHING*********************************")不显示

代码:

    var modelType = undefined;
    Anon.findOne({_id : app.locals.user._id})
    .then(function( returnAnonModel){
        console.log("returnAnonModel -----", returnAnonModel, "typeof : ", typeof returnAnonModel)
        if(err) console.log(err);
        if( Object.keys(returnAnonModel).length > 0 ){
            console.log("***********Anon USER SEARCHING*********************************")
            modelType = Anon
            userOrAnonArr()
        }else{
            console.log("***********USER USER SEARCHING*********************************")
            modelType = User
            userOrAnonArr(modelType)
        }
        function userOrAnonArr(modelType){
        console.log("modelType: ", modelType, " app.locals.user._id : ", typeof app.locals.user._id )
        modelType.findOne({_id : app.locals.user._id}, function(err, returnUser){
            if(err) console.log(err);
            console.log("returnUser : ", returnUser )

其他事情很奇怪:我试着通过这样做来测试对象的长度:console.log("Object.keys(returnAnonModel).length", Object.keys(returnAnonModel).length)

返回Object.keys(returnAnonModel).length 10,所以长度是10。我认为mongoose添加了属性

但当我这样做

console.log("Object.keys(returnAnonModel).length", Object.keys(returnAnonModel).toObject().length)

它绝对不会记录任何内容。为什么?

最后编辑

这工作。我一直在努力实现这个功能。我不知道为什么现在管用,而以前不行。我想这和控制台有关。

    var modelType = undefined;
    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){
            modelType = Anon;
            userOrAnonArr(modelType);
            console.log("*************Anon user found*********************");
        }else{
            modelType = User;
            userOrAnonArr(modelType);
            console.log("*************Anon user NOT found*************")
        }

Object.keys()函数不包含对象的所有属性。它只包含满足以下2个条件的属性:

  1. 属性必须是"owned"属性,这意味着Object.keys()查找任何可能存在的原型链。
  2. 该属性必须用enumerable属性定义。

从所提供的代码中不清楚returnAnonModel对象是如何构造的,但我的猜测是属性不满足所列出的两个标准。