【问题标题】:Loopback4 and MongoDB query documents with null or undefined fieldLoopback4 和 MongoDB 查询具有空或未定义字段的文档
【发布时间】:2019-08-31 08:45:21
【问题描述】:

如何查询字段为空或未定义的文档?

例如

{id:1, updatedAt: null}
{id:2}

我已经尝试过此代码无济于事。返回 0 个匹配项。

const whereBuilder = new WhereBuilder();
const where: Where = whereBuilder
  .eq('updatedAt', null)
//.eq('updatedAt', false)
  .build();

myRepository.findOne({
  where: where,
});

感谢您的帮助!

编辑 1:模型上的字段声明。

@property({
  type: 'date',
})
updatedAt?: string;

【问题讨论】:

    标签: loopbackjs loopback4


    【解决方案1】:

    在 MongoDB 外壳中

    使用$type 运算符匹配undefined 值,请参阅this

    // match `undefined`
    db.TEST.findOne({ updatedAt: {'$type':6}  });
    // match `null`
    db.TEST.findOne({ updatedAt: null  });
    

    在 LB4 中

    // match `undefined`
    return await this.myRepository.find(
        {
            where: {
                // !!!! "$" will be added automatically here. (explained below)
                updatedAt: { 'type': 6 }
            },
        }
    );
    // match `null`
    return await this.myRepository.find(
        {
            where: {
                updatedAt: null
            },
        }
    );
    

    为什么{ 'type': 6 }会被转换成{ '$type': 6 }

    ./node_modules/loopback-connector-mongodb/lib/mongodb.js 918 行:

    您的where 将在此函数中重构

    MongoDB.prototype.buildWhere = function(modelName, where, options) {
        ...
    

    在第 1011 行,{ 'type': 6 } 将转换为 { '$type': 6 }

       ...
          } else {
            query[k] = {};
            query[k]['$' + spec] = cond;
          }
       ...
    

    顺便说一下,在第 1016 行,你可以看到 null 将转换为 {$type: 10}

       ...
          if (cond === null) {
            // http://docs.mongodb.org/manual/reference/operator/query/type/
            // Null: 10
            query[k] = {$type: 10};
          } else {
       ...
    

    【讨论】:

    • 感谢您的快速回复。无法工作,因为该字段声明为:@property({ type: 'date', }) updatedAt?: string; 使用上面的代码时出现类型错误。
    • { where: { updatedAt: <Where<AnyObject>>{ 'type': 6 } }}{ where: { updatedAt: { 'type': 6 } as AnyObject }}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 2011-06-04
    • 2017-05-15
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多