3
votes

I want to use slugs (String) instead of ObjectID for some of my REST-exposed objects in Loopback

What the docs says about model ids:

By default, if no ID properties are defined and the idInjection of the model options is false, LDL automatically adds an id property to the model as follows:

id: {type: Number, generated: true, id: true}

I thought that I would just need to specify String as the type, and generated: false to avoid that loopback generates ObjectId instead.

id: { type: String, generated: false, id: true },

--> This did not work at all

In the code, mongodb.js I see that whatever the name of my id is, it is wrapped with an ObjectID function, which explains the loss of String value.

Side note : also, the generated property, is never used in mongodb connector code, what it is for?

My solution so far

Add a custom property (objectId, because I am not sure what generated is for) of my schema definition, which becomes :

id: {
    type: String, 
    objectId: false, 
    id: true
},

I then use this property as following, in [email protected]:155 :

var isObjectId = self.getDataSource(model)
                     .getModelDefinition(model)
                     .properties[idName]
                     .objectId;

if (idValue === null) {
    delete data[idName]; // Allow MongoDB to generate the id
} else {
    var oid = isObjectId ? ObjectID(idValue) : idValue; // Is it an Object ID?
    data._id = oid; // Set it to _id
    delete data[idName];
}

I updated save() method the same way, and now I can insert/modify objects with slug, and access them from the REST interface as well.

Question

I'm not sure this is right, will it break something?

Also, I don't really like the idea of modifying dependencies, so I would prefer to use an official method, or write a pull request if you guys at StrongLoop think you can make use of this.

1

1 Answers

3
votes

You should be able to use the following definition:

  1. To set the string id on the client side

    id: { type: String, generated: false, id: true }
    

or

  1. To use ObjectID as string

    id: { type: String, generated: true, id: true }
    

LoopBack mongodb connector tries to honor the id type. It only converts to ObjectID if the string format matches the ObjectID.

One bug was fixed recently but not released yet:

https://github.com/strongloop/loopback-connector-mongodb/pull/15

Please let us know on https://groups.google.com/forum/#!forum/loopbackjs if it doesn't for you.