[英]Don't know why the if condition is not detecting if the operand is an object or not
在此问题的底部,我有代码: console.log("returnAnonModel -----", returnAnonModel, "typeof : ", typeof returnAnonModel)
,它记录returnAnonModel
是一个对象。 我不明白为什么其他条件没有得到满足。
首先,让我向您展示它记录的内容:
returnAnonModel ----- { _id: 57d0d00c50ed1a2421749a69,
__v: 0,
usefulness: [],
reviews: [] } typeof : object
这个问题很直接。 您会看到对象,但显然在if条件不为true的情况下Object.keys(returnAnonModel).length > 0
。 对象的长度不应该为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。我认为猫鼬会添加属性。
但是当我这样做
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个条件的属性:
Object.keys()
不沿着任何可能存在的原型链的样子。 enumerable
属性定义。 从提供的代码尚不清楚returnAnonModel
对象是如何构造的,但是我的猜测是这些属性不能同时满足列出的两个条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.