【问题标题】:i can't query over populated children attributes我无法查询填充的子属性
【发布时间】:2020-12-20 22:19:58
【问题描述】:

我正在尝试使用 mongoose 查询填充的子属性,但它直接不起作用,并且会一直返回空数组。

即使将权利和现有信息硬编码为查询值,也会返回空数组。

我的架构是通过属性 createdBy 与用户架构一对一关系的业务架构。用户架构有一个我正在尝试查询的属性名称。

所以如果我这样查询:

business.find({'createdBy.name': {$regex:"steve"}}).populate('createdBy')

以上将永远不会返回任何文件。虽然,没有 find 条件,一切正常。

我是否可以通过填充孩子中的姓名进行搜索?所有教程都说这应该可以正常工作,但事实并非如此。

编辑:记录的示例:

{
            "_id": "5fddedd00e8a7e069085964f",
            "status": 6,
            "addInfo": "",
            "descProduit": "",
            "createdBy": {
              "_id": "5f99b1bea9ba194dec3bd6aa",
              "status": 1,
              "fcmtokens": [
                
              ],
              "emailVerified": 1,
              "phoneVerified": 0,
              "userType": "User",
              "name": "steve buschemi",
              "firstName": "steve",
              "lastName": "buschemi",
              "tel": "",
              "email": "steve@buschemi.com",
              "register_token": "747f1e1e8fa1ecd2f1797bb402563198",
              "createdAt": "2020-10-28T18:00:30.814Z",
              "updatedAt": "2020-12-18T13:52:07.430Z",
              "__v": 19,
              "business": "5f99b1e101bfff39a8259457",
              "credit": 635,
            },
            "createdAt": "2020-12-19T12:10:57.703Z",
            "updatedAt": "2020-12-19T12:11:16.538Z",
            "__v": 0,
            "nid": "187"
          }

【问题讨论】:

  • 您能否从business集合中添加至少一条满足您条件的记录?
  • @Anatoly 我不明白我们为什么需要它,但相信我,我确信我已经尝试解决这个问题一段时间了
  • 也许你的意思是使用business.find().populate({path:'createdBy', match: {name: {$regex:"steve"}}})
  • 我的意思是你在你的帖子中显示一条记录的内容应该满足你在find中的条件?我尝试了类似的请求并且成功了。
  • 我有记录{ "_id": { "$oid": "5f229fee6d04771448e02611" }, "title": "Book3", "author": { "name": "Author6", "age": 21 }, "__v": 0 },我试过const result = await Book.find({'author.name': {$regex:"Author"}}).populate('author').exec()

标签: node.js mongodb mongoose


【解决方案1】:

似乎没有办法根据子文档的条件过滤父文档:

来自official documentation

一般来说,没有办法根据故事作者的属性使 populate() 过滤故事。例如,以下查询不会返回任何结果,即使作者已填充。

const story = await Story.
  findOne({ 'author.name': 'Ian Fleming' }).
  populate('author').
  exec();

story; // null

如果您想按作者姓名过滤故事,您应该使用denormalization

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    相关资源
    最近更新 更多