loopback icon indicating copy to clipboard operation
loopback copied to clipboard

PersistedModel.findOne's API unexpected behavior in querying MongoDB property whose type is ObjectId with where filter

Open ZenStudioLab opened this issue 9 years ago • 11 comments

According to loopback's findOne API documentation here, a where clause is needed in a findOne query. However, the it turns out that in a MongoDB query with where filter of which property type is ObjectId, keeping where filter results in a null response. While removing where from filter actually makes thing work!

Query with where filter

Description/Steps to reproduce

app.models.SocialNewsFeed.findOne({
    where: {
	feedId: {eq: "595ef24b7f136e0750f95d9c"}	
    }
}).then(result => {
    logger.debug(result);
});

Expected result

{ consumerId: 2,
  verb: 1,
  feedId: '595ef24b7f136e0750f95d9c',
  createdAt: '1499394635',
  producerId: 10,
  id: 595ef24b7f136e0750f95d9d }

Actual result

null

Now let us remove where from query filter

Description/Steps to reproduce

app.models.SocialNewsFeed.findOne({
	feedId: {eq: "595ef24b7f136e0750f95d9c"}	
}).then(result => {
    logger.debug(result);
});

Expected result

null

Actual result

{ consumerId: 2,
  verb: 1,
  feedId: '595ef24b7f136e0750f95d9c',
  createdAt: '1499394635',
  producerId: 10,
  id: 595ef24b7f136e0750f95d9d }

Additional information

System & project information

linux x64 7.9.0

├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]

Model.json

  "properties": {
    "id": {
      "type": "string",
      "required": true
    },
    "consumerId": {
      "type": "number",
      "required": true
    },
    "producerId": {
      "type": "number",
      "required": true
    },      
    "verb": {
      "type": "number",
      "required": true
    },
    "feedId": {
      "type": "string"
    },
    "createdAt": {
      "type": "string",
      "required": true
    }
  },

ZenStudioLab avatar Aug 07 '17 08:08 ZenStudioLab

I'll take a look at this later tonight and attempt to reproduce.

kjdelisle avatar Aug 15 '17 19:08 kjdelisle

So far, with a simpler model, I've had no luck: Foo.js

'use strict';

module.exports = function(Foo) {
  Foo.findBar = function(fooId, next) {
    Foo.app.models.Bar.findOne({
      where: {
        fooId: fooId,
      },
    }).then(bar => {
      return next(null, bar);
    }).catch(err => {
      return next(err);
    });
  };

  // Wire up a custom remote method just to test this out.
  Foo.remoteMethod('findBar', {
    accepts: {arg: 'fooId', type: 'string'},
    returns: {arg: 'bar', type: 'Bar'},
  });
};

This seems to return a matching Bar instance as expected. I'm going to attempt to match your reproduction with your model def and see if it changes anything.

kjdelisle avatar Aug 16 '17 19:08 kjdelisle

@fluteguitar When you called findOne, were you doing it from a remote method context, or from a CRUD method's operation hook? I want to make sure I'm following along as closely as possible.

kjdelisle avatar Aug 16 '17 19:08 kjdelisle

After using your model definition, I can confirm your reproduction.

kjdelisle avatar Aug 16 '17 19:08 kjdelisle

What's interesting is that if I mirror the logic of my previous synthetic attempt with the Bar model, I don't see the same results:

   // Note that I didn't use the "eq" operator.
    Customer.app.models.SocialNewsFeed.findOne({
      where: {
        feedId: feedId,
      },
    }).then(bar => {
      return next(null, bar);
    }).catch(err => {
      return next(err);
    });

kjdelisle avatar Aug 16 '17 19:08 kjdelisle

@fluteguitar After reading the mongodb connector readme, I made some changes to the model-definition you've sent as an example:

{
  "name": "SocialNewsFeed",
  "base": "PersistedModel",
  "idInjection": false,
  "options": {
    "validateUpsert": true,
    "strictObjectIDCoercion": true
  },
  "properties": {
    "consumerId": {
      "type": "number",
      "required": true
    },
    "producerId": {
      "type": "number",
      "required": true
    },
    "verb": {
      "type": "number",
      "required": true
    },
    "feedId": {
      "type": "string"
    },
    "createdAt": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": {}
}

With this definition, the .findOne call I made in my last comment works. @ssh24 Do you know why these changes might be required for findOne to operate correctly? The documentation as I've read it doesn't seem to imply that this configuration is required for querying, only that it's necessary to prevent coercion of the wrong strings into ObjectIDs.

kjdelisle avatar Aug 16 '17 19:08 kjdelisle

The original issue has nothing to do with ObjectID's in MongoDB. eq is not a supported loopback operator. For a list of supported operators, please refer here.

In this case, the filter should be {where: {feedId: "595ef24b7f136e0750f95d9c"}}.

ssh24 avatar Aug 16 '17 21:08 ssh24

@ssh24 My mistake! @fluteguitar If this doesn't solve your issue, let me know and I'll reopen this.

kjdelisle avatar Aug 16 '17 21:08 kjdelisle

@kjdelisle I tried this new script, by modifying findOne to find @ssh24 It seems that "strictObjectIDCoercion": true is a required condition.

app.models.SocialNewsFeed.find({
    where: {
	feedId: "595ef24b7f136e0750f95d9c"
    }
}).then(result => {
    logger.debug(result);
    process.exit();
});
    

Now without "strictObjectIDCoercion": true in Model.json, the result is

[]

Now with "strictObjectIDCoercion": true in Model.json, the result is as expected.

[ { consumerId: 5,
    verb: 1,
    feedId: '595ef24b7f136e0750f95d9c',
    createdAt: '1499394635',
    producerId: 10,
    id: 595ef24b7f136e0750f95d9e },
  { consumerId: 7,
    verb: 1,
    feedId: '595ef24b7f136e0750f95d9c',
    createdAt: '1499394635',
    producerId: 10,
    id: 595ef24b7f136e0750f95d9f },
  { consumerId: 10,
    verb: 1,
    feedId: '595ef24b7f136e0750f95d9c',
    createdAt: '1499394635',
    producerId: 10,
....

ZenStudioLab avatar Aug 17 '17 09:08 ZenStudioLab

My other observation is that, without where filter, findOne will return a random model (The result could be a model whose feedId is as same as feedId value in the query, Loopback seems not to care about other fields in the query. Here I am not sure since I dont have time to test all the cases).

Script

app.models.SocialNewsFeed.findOne({
    //    where: {
    consumerId: 7,    
    feedId: {eq:"595ef24b7f136e0750f95d9c"}
//    }
}).then(result => {
    logger.debug(result);
    process.exit();
});

Another script, but without eq.

app.models.SocialNewsFeed.findOne({
    //    where: {
    consumerId: 7,    
    feedId: "595ef24b7f136e0750f95d9c"
//    }
}).then(result => {
    logger.debug(result);
    process.exit();
});

Expected result

  { consumerId: 7,
    verb: 1,
    feedId: '595ef24b7f136e0750f95d9c',
    createdAt: '1499394635',
    producerId: 10,
    id: 595ef24b7f136e0750f95d9f }

Actual result are the same for both test (unexpected)

Note consumerId should be 7 instead of 5.

{ consumerId: 5,
    verb: 1,
    feedId: '595ef24b7f136e0750f95d9c',
    createdAt: '1499394635',
    producerId: 10,
    id: 595ef24b7f136e0750f95d9e }

social-news-feed.json

{
    "name": "SocialNewsFeed",
    "base": "Model",
    "http": {
	"path": "Social/newsfeed"
    },
    "mongodb": {
	"collection": "social_newsfeed"
    },
    "idInjection": true,
    "options": {
	"strictObjectIDCoercion": true,	
	"validateUpsert": true
    },
    "properties": {
	"id": {
	    "type": "string",
	    "required": true
	},
	"consumerId": {
	    "type": "number",
	    "required": true
	},
	"producerId": {
	    "type": "number",
	    "required": true
	},      
	"verb": {
	    "type": "number",
	    "required": true
	},
	"feedId": {
	    "type": "string"
	},
	"createdAt": {
	    "type": "string",
	    "required": true
	}
    },
    "validations": [],
    "relations": {
	"feed_post": {
	    "type": "hasOne",
	    "model": "SocialPost",
	    "foreignKey": "feedId"
	}
    },
    "acls": [
	{
	    "accessType": "*",
	    "principalType": "ROLE",
	    "principalId": "$everyone",
	    "permission": "DENY"
	},
	{
	    "accessType": "EXECUTE",
	    "principalType": "ROLE",
	    "principalId": "$authenticated",
	    "permission": "ALLOW",
	    "property": "getUserNewsFeed"
	},
	{
	    "accessType": "EXECUTE",
	    "principalType": "ROLE",
	    "principalId": "$authenticated",
	    "permission": "ALLOW",
	    "property": "getHomePage"
	},
	{
	    "accessType": "EXECUTE",
	    "principalType": "ROLE",
	    "principalId": "$authenticated",
	    "permission": "ALLOW",
	    "property": "getUserInfo"
	}   
    ],
    "methods": {}
}

ZenStudioLab avatar Aug 17 '17 09:08 ZenStudioLab

app.models.SocialNewsFeed.findOne({
    //    where: {
    consumerId: 7,    
    feedId: "595ef24b7f136e0750f95d9c"
//    }
}).then(result => {
    logger.debug(result);
    process.exit();
});

If you omit the where clause, it won't leverage the properties you passed in as constraints; it only looks for those constraints under the appropriate properties (like where).

kjdelisle avatar Aug 17 '17 22:08 kjdelisle