0

in my sails controller I have implement a function to find users. but when I try to search using ObjectId it returns all the data. I couldn't find any reason. but it works when I create a new separate field as "userID", and find using "userID". I think the problem is find using the "ObjectId" what could be the issue.

module.exports = {

    updateOrders : function(req,res){

    var ObjectId = require('mongodb').ObjectID;
    console.log("req " + req);
    var data = req.body;
    var obj = [];


console.log("\ndata "+(data));

var jdata = JSON.stringify(data);
console.log("\njdata: "+jdata);

    data.forEach(function(orders){

        var objid = ObjectId(orders.id);
        console.log("Obj orders id  :" + objid);


        ApplicationOrder.find({id: ObjectId(orders.id)}).exec(function (err, order) {

            if (err){
                return done(err);
            }

            console.log('order ' + order);
             obj.push(order);
        });


    })
        res.send(obj);




        }


};

Json data: printed in the console.

{
    "_id" : ObjectId("59a8f820caf1cae37af72c0c"),
    "appId" : "59a669431954a69e37c20b69",
    "registeredUser" : "59a677811954a69e37c20b73",
    "item" : [ 
        {
            "id" : "59a669441954a69e37c20b70",
            "name" : "Short x",
            "qty" : 1,
            "sku" : "1111",
            "totWeight" : null,
            "price" : "250",
            "total" : "250",
            "imgURL" : [ 
                {
                    "img" : "short_x.png"
                }
            ],
            "totalQty" : 218
        }
    ],
    "amount" : "250",
    "customerName" : "dilakshan",
    "deliverName" : "dilakshan",
    "deliveryNo" : "11010",
    "deliveryStreet" : "delgoda",
    "deliveryCity" : "kandana",
    "deliveryCountry" : "Sri Lanka",
    "deliveryZip" : "11010",
    "telNumber" : 94779967409,
    "tax" : "0",
    "shippingCost" : "0",
    "shippingOpt" : "Flat Rate",
    "email" : "s.dilakshan@yahoo.com",
    "currency" : "$",
    "paymentStatus" : "Pending",
    "fulfillmentStatus" : "Pending",
    "createdAt" : ISODate("2017-09-01T06:03:12.584Z"),
    "updatedAt" : ISODate("2017-09-01T06:03:12.584Z")
}
{
    "_id" : ObjectId("59a8f82fcaf1cae37af72c0d"),
    "appId" : "59a669431954a69e37c20b69",
    "registeredUser" : "59a677811954a69e37c20b73",
    "item" : [ 
        {
            "id" : "59a669441954a69e37c20b6d",
            "name" : "Shirt x",
            "qty" : 1,
            "sku" : "1111",
            "totWeight" : null,
            "price" : "250",
            "total" : "250",
            "imgURL" : [ 
                {
                    "img" : "shirt_x.png"
                }
            ],
            "totalQty" : 244
        }
    ],
    "amount" : "250",
    "customerName" : "dilakshan",
    "deliverName" : "dilakshan",
    "deliveryNo" : "11010",
    "deliveryStreet" : "delgoda",
    "deliveryCity" : "kandana",
    "deliveryCountry" : "Sri Lanka",
    "deliveryZip" : "11010",
    "telNumber" : 94779967409,
    "tax" : "0",
    "shippingCost" : "0",
    "shippingOpt" : "Flat Rate",
    "email" : "s.dilakshan@yahoo.com",
    "currency" : "$",
    "paymentStatus" : "Pending",
    "fulfillmentStatus" : "Pending",
    "createdAt" : ISODate("2017-09-01T06:03:27.022Z"),
    "updatedAt" : ISODate("2017-09-01T06:03:27.022Z")
}
{
    "_id" : ObjectId("59a8f83ecaf1cae37af72c0e"),
    "appId" : "59a669431954a69e37c20b69",
    "registeredUser" : "59a677811954a69e37c20b73",
    "item" : [ 
        {
            "id" : "59a669441954a69e37c20b71",
            "name" : "Beach Suit",
            "qty" : 2,
            "sku" : "1111",
            "totWeight" : null,
            "price" : "250",
            "total" : "250",
            "imgURL" : [ 
                {
                    "img" : "cloth3.png"
                }
            ],
            "totalQty" : 238
        }
    ],
    "amount" : "500",
    "customerName" : "dilakshan",
    "deliverName" : "dilakshan",
    "deliveryNo" : "11010",
    "deliveryStreet" : "delgoda",
    "deliveryCity" : "kandana",
    "deliveryCountry" : "Sri Lanka",
    "deliveryZip" : "11010",
    "telNumber" : 94779967409,
    "tax" : "0",
    "shippingCost" : "0",
    "shippingOpt" : "Flat Rate",
    "email" : "s.dilakshan@yahoo.com",
    "currency" : "$",
    "paymentStatus" : "Pending",
    "fulfillmentStatus" : "Pending",
    "createdAt" : ISODate("2017-09-01T06:03:42.439Z"),
    "updatedAt" : ISODate("2017-09-01T06:03:42.439Z")
}
  • Can you please be more clear about what your code does and what you are expecting it to do? You mention that the controller action should "find users" and I see the a `registeredUser` ID is returned with each ApplicationOrder row queried. Is the desired behavior different than this? – ContinuousLoad Sep 01 '17 at 19:33
  • **registeredUser** ID is for a particular user who logged in. it will differ from user to user when they signup. in this criteria its for a selected products also having a unique **id**. the problem is when I use the ObjectId to find the particular data it returns all the other data. – Dilakshan Sooriyanathan Sep 04 '17 at 04:12
  • Thanks for the update! Have you tried specifying `_id` like this: `ApplicationOrder.find({'_id': orders. Id})...`? Also remember that `.find` returns (thru the callback) results as an array, so `order` in your code would really be `orders`. – ContinuousLoad Sep 05 '17 at 01:51

3 Answers3

1

For standard sails.js/waterline queries, you have to use the id as a String in your query params, do not use ObjectId(ordersId).

When you use a sails native query, use ObjectId(ordersId).

Manuel Reil
  • 508
  • 2
  • 10
  • I have tried that it returns no result for me. but I was able to print my parsed "order.id" value. when I use` {id:orders.id}` it gives me no data. It only returns some data when I use only **ObjectId**. but it returns all the other datas. – Dilakshan Sooriyanathan Sep 04 '17 at 04:12
  • I guess orders is an array, is it? You need to retrieve it properly so that the id is a String or and array of Strings. – Manuel Reil Sep 04 '17 at 04:55
  • yes _order_ is an array. the thing is **.find** criteria returns all the objects in my mongodb database. it's not returning the object that I specified with the ObjectId. thts what I have printed in the console as **returned Objects** in my function. – Dilakshan Sooriyanathan Sep 04 '17 at 06:13
  • Use findById(orders.id) method once – Tejas Jain Sep 04 '17 at 06:51
  • If orders is an array of objects, then of course orders.id does not work. You need to retrieve id one by one from each object and put it in a new array. I am using lodash: let orderIds = _.map(orders, 'id'); – Manuel Reil Sep 04 '17 at 06:55
  • I am sure doing `orders.id` is the error. An array does not have a key `id`, only an object could have one. So get all the ids like explained in my previous comment. – Manuel Reil Sep 05 '17 at 11:20
1

If you are using any mongodb adapter then do not try to convert id by ObjectId(orders.id).Try normal query like

 ApplicationOrder.find({'id':orders.id})

For native sails query,you have to convert id to objectId.

Tejas Jain
  • 162
  • 1
  • 8
  • I have tried that it returns no result for me. but I was able to print my parsed "order.id" value. when I use` {id:orders.id}` it gives me no data. It only returns some data when I use only **ObjectId**. but it returns all the other datas. Also I have found something. when I delete the 'id' data field from the parsed JSON data it still returns me all the objects. – Dilakshan Sooriyanathan Sep 04 '17 at 04:00
  • `ApplicationOrder.native(function(err, collection) { if (err) return res.serverError(err); collection.find({'_id':ObjectId(orders.id)}).toArray(function (err, results) { if (err) return res.serverError(err); console.log(results); return res.ok(results); }); })` **this code returns me** _TypeError: Argument must be a string _ – Dilakshan Sooriyanathan Sep 04 '17 at 04:46
  • Use findById(orders.id) method once – Tejas Jain Sep 04 '17 at 06:52
0

I finally was able to fix the issue. I had to edit the my model class in sails and use only orders.id model class,

_id:{type : 'objectid'} and when search

.find({_id: orders.id})

this worked for me perfectly.