sailsjs array query Exact match

跟風遠走 提交于 2019-12-11 03:16:46

问题


i want to query mongodb in sailsjs. this is structure of my db

{
    "users": [
        "52ed09e1d015533c124015d5",
        "52ed4bc75ece1fb013fed7f5"
    ],
    "user_msgs": [
        {
            "sender": "52ed09e1d015533c124015d5",
            "sendTo": "52ed4bc75ece1fb013fed7f5",
            "msg": "ss"
        }
    ],
    "createdAt": ISODate("2014-02-06T16:12:17.751Z"),
    "updatedAt": ISODate("2014-02-06T16:12:17.751Z"),
    "_id": ObjectID("52f3b461f46da23c111582f6")
}

I want to search those "users" who who match array

  [
        "52ed09e1d015533c124015d5",
        "52ed4bc75ece1fb013fed7f5"
    ]
Message.find({user: ["52ed09e1d015533c124015d5","52ed4bc75ece1fb013fed7f5"]})

this query returns all objects which contains 1 OR 2 ..but i need only those which exacly match 1 AND 2, i have also tried $all, and etc.. but did not worked please tell me how to write query with sailsjs supported syntex to get those user

回答1:


You'll need to use the native Mongo adapter for this:

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
});

While the above code may work to pull in just those users. I think a better solution would be to define your user ID's in your message model.

I would add the following attributes to your messages model:

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

Now you can make that query more efficient by using the following query:

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

This is the route I would take.



来源:https://stackoverflow.com/questions/21608919/sailsjs-array-query-exact-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!