检查猫鼬对象是否包含子字段的函数
问题描述:
以下代码无法正常工作,我想在我的猫鼬findOne查询后检查是否定义了对象中的某个子文档。检查猫鼬对象是否包含子字段的函数
function cleanIfAny(social, value) {
var name = social + '.id';
var query = {};
query[name] = value;
User.findOne(query, function (err, found) {
if (err) console.log(err);
// if the account is already linked somewhere else
if (found) {
// detach it from there
found[social] = undefined;
// TODO Check if field in document is present
console.log(found.local + ' ' + found.google + ' ' + found.facebook);
console.log(isEmpty(found.local)+ ' ' + isEmpty(found.google) + ' ' + isEmpty(found.facebook));
if(isEmpty(found.local) && isEmpty(found.google) && isEmpty(found.facebook)) {
console.log('no more account attached deleting');
found.remove();
} else {
console.log('ok unlink the account');
found.save(function (err) {
if (err) console.log(err);
})
}
}
})
}
function isEmpty(obj) {
return (obj == null || Object.keys(obj).length === 0);
}
此代码返回
{} { token: 'abcdefgh, name: 'FirstName LastName', id: '123456789', email: '[email protected]' } undefined
false false false
ok unlink the account
预期与我的isEmpty(
取而代之的是
true false true
但是我已经尽了功能这个范围之外的一些简单的变量和一切工作)功能。
我只是试着用lodash得到的结果在我的函数里面是一样的: 也许由mongoose返回的格式不是我期望的或者是在整个函数中有什么不好的。 – melkir
在我的情况下,typeof found,found.local,found.google和found.facebook是对象,即使未定义的 – melkir
猫鼬文档具有存储实际mongo对象的'_doc'属性。关键不是顶级。我认为检查'doc.property === undefined'应该可以。 – cdbajorin