【问题标题】:sailsjs array query Exact matchSailsjs 数组查询精确匹配
【发布时间】:2014-02-06 16:46:37
【问题描述】:

我想在sailsjs 中查询mongodb。 这是我的数据库的结构

{ “用户”:[ "52ed09e1d015533c124015d5", “52ed4bc75ece1fb013fed7f5” ], “user_msgs”:[ { “发件人”:“52ed09e1d015533c124015d5”, "sendTo": "52ed4bc75ece1fb013fed7f5", “味精”:“ss” } ], "createdAt": ISODate("2014-02-06T16:12:17.751Z"), "updatedAt": ISODate("2014-02-06T16:12:17.751Z"), "_id": ObjectID("52f3b461f46da23c111582f6") }

我要搜索那些匹配数组的“用户”

[ "52ed09e1d015533c124015d5", “52ed4bc75ece1fb013fed7f5” ] Message.find({user: ["52ed09e1d015533c124015d5","52ed4bc75ece1fb013fed7f5"]})
此查询返回包含 1 OR 2 的所有对象 ..但我只需要完全匹配 1 AND 2 的对象, 我也尝试过 $all 等。但没有奏效 请告诉我如何使用sailsjs 支持的语法编写查询来获取这些用户

【问题讨论】:

    标签: sails.js waterline


    【解决方案1】:

    您需要为此使用本机 Mongo 适配器:

    Message.native(function(err, collection) {
    
       collection.find({users:{'$all':["52ed09e1d015533c124015d5","52ed4bc75ece1fb013fed7f5"]}}).toArray(function(err, results) {
    
         // Do something with results
    
       });
    
    });
    

    【讨论】:

      【解决方案2】:
      Message.find()
      .where({users: "52ed09e1d015533c124015d5", "52ed4bc75ece1fb013fed7f5"})
      .exec(function(){
        // do something
      });
      

      虽然上面的代码可能只吸引这些用户。我认为更好的解决方案是在消息模型中定义您的用户 ID。

      我会在您的消息模型中添加以下属性:

      senderID: {
         type: 'string'
      },
      receiverID: {
         type: 'string'
      }
      

      现在您可以使用以下查询使查询更高效:

      Message.find()
      .where({senderID: "52ed09e1d015533c124015d5"})
      .where({receiverID: "52ed4bc75ece1fb013fed7f5"})
      .exec(function(){
        // do something
      });
      

      这是我要走的路。

      【讨论】:

      • 感谢您的回答。但它对我不起作用。我为 mongodb 制作的上述模式允许 1-1 和多用户聊天..就像组对话一样。在“用户”数组中我想 stroe 那些在这个聊天中的用户 ID。在检索数据时我想要 EXACT 数组of user.. where 还返回所有拥有其中之一的对象
      • 这是不正确的语法:.where({users: "52ed09e1d015533c124015d5", "52ed4bc75ece1fb013fed7f5"})
      猜你喜欢
      • 1970-01-01
      • 2017-03-02
      • 1970-01-01
      • 2016-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多