Reputation: 6413
I'm experimenting with Ruby (which I don't know very well) and Mongo (which I do.) I've made a Mongoid model with an :accessed
field. I know that in Mongo I can just run something like:
data = db.collection.findAndModify({
query: { ... },
update: {$inc: {accessed: 1}}
})
But when I run MyModel.collection.find_and_modify
in Mongoid, I get back what appears to be a hash. Is there a way I can coerce this into an instance of my model class, or do a better supported query in Mongoid?
Upvotes: 0
Views: 1355
Reputation: 65887
By default find_and_modify returns the hash, check the documentation
Parameters:
Options Hash (opts):
Returns:
But you can convert the hash to your collection object by simply initializing the model by passing the hash as a argument
>> x = MyModel.collection.find_and_modify(:query => {...},:update => {...})
>> x.class
>> BSON::OrderedHash
>> obj = MyModel.new(x)
>> obj.class
>> MyModel
And now you can apply any mongoid operation on the converted object. It will work perfectly.
Hope it helps
Upvotes: 1