Reputation: 5260
I have a model looks like this
var mongoose = require('mongoose');
var tableSchema = new mongoose.Schema({
version: { type: String, uppercase: true , required: true, trim: true },
name: { type: String, uppercase: true , required: true, trim: true },
descr: String
});
uctableSchema.index({ version: 1, name: 1 }, { unique: true });
module.exports = mongoose.model('Table', tableSchema);
This model will generate a collection like this
> db.tables.findOne()
{
"_id" : ObjectId("56fc97d6e81ed6faf5e75b58"),
"version" : "4",
"name" : "address",
"descr" : "contact address table"
}
That's all fine. I intentionally to leave mongoose to generate auto _id.
And I create a unique composite index to serve as primary key.
The data is actually imported from RDBMS via json file. So mongoimport will auto-generate _id for it. And that is fine.
The _id value does not have real meaning and I would like to retrieve, modify, and delete data by the composite primary key.
In my case, can I still use findById?
Model.findById(id, [projection], [options], [callback])
Model.findByIdAndUpdate(id, [update], [options], [callback])
Model.findByIdAndRemove(id, [options], [callback])
I understand that the first parameter id refers to _id that I don't want to use.
Is there a work around to make id parameter to refer to my composite key, version and name? Or I shouldn't use findById at all in my case?
Thanks,
Upvotes: 2
Views: 268
Reputation: 311865
Nope, the xxxById methods are all designed to work with _id
only.
For example, here's the source for findById
:
Model.findById = function findById(id, projection, options, callback) {
if (typeof id === 'undefined') {
id = null;
}
return this.findOne({_id: id}, projection, options, callback);
};
You'll need to use the more general findOne
, findOneAndUpdate
, and findOneAndRemove
methods.
Upvotes: 2