【问题标题】:Find documents that contain certain value for sub-object field Mongoose查找包含子对象字段 Mongoose 特定值的文档
【发布时间】:2016-04-04 13:26:42
【问题描述】:

注意:我问过这个问题here,但是当时我纯粹是在使用MongoDB,现在我正在尝试使用@987654323 来实现这个@。我决定提出一个单独的问题是合适的,因为我相信答案会完全不同,但是如果我的决定有误,请告诉我。


我有一个格式如下的集合:

[ 
  {
     firstname: 'Joe',
     lastname: 'Blow',
     emails: [
       {
          email: 'test@example.com',
          valid: false
       },
       {
          email: 'test2@example.com',
          valid: false
       }
     ],
     password: 'abc123',
     _id: 57017e173915101e0ad5d94a
  },
  {
     firstname: 'Johnny',
     lastname: 'Doe',
     emails: [
       {
          email: 'test3@example.com',
          valid: false
       }
     ],
     password: 'abc123',
     _id: 57017e173915101e0ad5d87b
  },
]

我正在尝试根据emails.email 字段查找用户。这是我目前所拥有的:

UserModel.find()
         .where('emails')
         .elemMatch(function (elem) {
           elem.where('email').equals(userEmail);
         })
         .limit(1)
         .exec(
         (err, usersReturned) => {
           console.log('test2@example.com');
         });

我做错了什么?我是 Mongoose 的新手,似乎无法弄清楚这一点。

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    你可以这样做:

    UserModel.find({"emails.email": userEmail}).limit(1).exec(function(err, user){
        if(err) console.log("Error: " + JSON.stringify(err));
        else if(user) console.log("User Returned is : " + JSON.stringify(user));
    });
    

    【讨论】:

      【解决方案2】:

      您可以使用 Mongodb aggregate 函数。在 "emails.email" 字段上使用 $unwind 它将将数组分隔为独立的文档。

      UserModel.aggregate( [
          { $unwind : "$emails" },
          { $match: {$emails.email:"email you want to put"}}
      ],function(err,result){    
          //write code but you want to do
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-06-07
        • 1970-01-01
        • 1970-01-01
        • 2014-12-16
        • 2016-04-23
        • 2020-04-19
        相关资源
        最近更新 更多