如何在填充的mongodb中实现查找?

时间:2019-05-27 01:51:44

标签: mongodb mongoose aggregate

所以问题继续yesterday,我又遇到了一个新问题

我已经阅读了文档,从中我得到正确的搜索功能,就是使用$match

当我实现它时,在使用mongoose上的find方法之前,我没有得到想要的数据。

如果聚合可以做到,那么如何实现呢?预先谢谢你

 const accounts = await Account.find({
        //  query      database             query
        ...(_id    && {_id    : { $in    : _id.split(",")    }}),
        ...(name   && {$text  : { $search: name           }}),
        ...(email  && {email  : { $in    : email.split(",")  }}),
        ...(phone  && {phone  : { $in    : phone.split(",")  }}),
        ...(status && {status : { $in    : status.split(",") }}),
  });

  const newAcc = await accounts.map(async account => {
    const accMeta = await AccountMeta.find({ 
        ...({account_id        : account._id}),
        ...(ac_key   && {key   : ac_key}),
        ...(ac_value && {value : ac_value})
   });

fyi:在使用聚合之前,由于account_meta部分的限制,在上面的示例中,我使用了由javascript完成的合并对象,因此我尝试将其合并以合并

这是我的汇总:

exports.get_Account = async (req, res) => {
  const { _id, name, email, phone, status, value } = req.query

  console.log(req.query)

  const result = await Account.aggregate([
    {
        $lookup      : {
            from         : "account_meta",
            localField   : "_id",
            foreignField : "account_id",
            as           : "metas"
        }
    },
    { "$unwind": "$metas" },
    {
        $group   : {
            _id      : "$_id",
            name     : {$first: "$name"     },
            status   : {$first: "$status"   },
            email    : {$first: "$email"    },
            password : {$first: "$password" },
            data     : {
            "$push"  : {
                "k"      : "$metas.key",
                "v"      : "$metas.value"
                }
            }
        }
    },
    {
        $project       : {
            "_id"          : "$_id",
            "name"         : "$name",
            "email"        : "$email",
            "status"       : "$status",
            "password"     : "$password",
            "metas"        : {
                $arrayToObject : "$data"
                    }
        }
    },
    {
        "$replaceRoot": {
            "newRoot":
                {
                    "$mergeObjects": [ "$$ROOT",'$metas']
                },
        }
    },
    {
      $match: 
      {
          $or      : [
              { value  : value  },
              { _id    : _id    },
              { email  : email  },
              { phone  : phone  },
              { status : status },
          ],
      }
    },
    {
        $project : {
            metas: 0
        }
    },

  ])
  res.json(result)
};

添加结果:

[
    {
        "_id": "5ce8981a46039c14a4ec32d1",
        "name": "Monkey D Luffy",
        "email": "aaa@aaa.com",
        "status": "not verified",
        "password": "$2a$10$ayluBIsOOelBTIk.69GjHubgQemr6dJfgBUELNusCOaUGLpS/qKs6",
        "role": "admin",
        "smartphone": "ios",
        "alamat": "jogja",
        "hobi": "mancing"
    },
    {
        "_id": "5ce8980b46039c14a4ec32cf",
        "name": "Monkey D Law",
        "email": "ccc@ccc.com",
        "status": "not verified",
        "password": "$2a$10$t7pqvWTzagSWCFtW.d3vnOmR.r5mgZ4jTZEx3IA1X2aeWUn/76Yq6",
        "role": "admin",
        "laptop": "asus",
        "mobil": "toyota"
    },
    {
        "_id": "5ce897fc46039c14a4ec32cd",
        "name": "Monkey D Dragon",
        "email": "ddd@ddd.com",
        "status": "not verified",
        "password": "$2a$10$5X75lGHkMydRZb6tCLgOsO0cvZZyc8z2vllTmgbpw9WKL3VGivrse",
        "role": "admin",
        "gender": "perempuan",
        "smartphone": "android"
    }
]

我希望在两种情况下得到的结果是相同的,但是使用.find方法和带有javascript的合并对象时,我无法搜索account_meta ,请参阅以下角色的结果, 我正在寻找其他方法来聚集并成功。现在的问题是查找汇总的实现

更新:我将我的方法从聚合更改回填充

exports.get_Account = async (req, res) => {
  let { _id, name, email, phone, status, value, value_else, key } = req.query 

        console.log('value type', typeof value)
        console.log('value_else type', typeof value_else)
        value         = value + '' ? value.split(',')           : value
        value_else    = value_else + '' ? value_else.split(',') : value_else
        // value_else = == undefined ? null      : ''

        console.log('value', value)
        console.log('value else', value_else)

        let orUserMeta = [], orUserMetaElse = [];

        _.forEach(value,str => {
            orUserMeta = [ ...orUserMeta, { value: str } ]
        })
        console.log('usrmeta', orUserMeta)

        _.forEach(value_else,str => {
          orUserMetaElse = [ ...orUserMetaElse, { value: str } ]
        })
        console.log('usermetaElse', orUserMetaElse)

  const accountMeta = await AccountMeta.find({

        ...(_id        && { _id }),
        ...(key        && { key }),
        ...( value     && { $or :  orUserMeta }), //failed
        ...(value_else && { $nor : orUserMetaElse }) // failed
  }).lean().populate({
    path   : 'account_id',
    select : '-password',
    match  : {
      ...(email   && { email }),
      ...(phone   && { phone }),
      ...(status  && { status }),
      ...(name    && {$text  : { $search: name }})
      }
  })


  res.json(accountMeta)
}

现在,我的问题是,用$ nor或$找不到,或者当我命中邮递员时导致值分离。.当我变成数组时,出现错误split is undefined。有什么线索或提示吗?预先感谢

0 个答案:

没有答案