Permalink
Browse files

handle DocArray#id when doc has no id

closes #897
  • Loading branch information...
aheckmann committed May 7, 2012
1 parent 36b05a3 commit 2385a924ae5d2e869fc0903e66956fe0ee5c6882
Showing with 29 additions and 5 deletions.
  1. +9 −5 lib/types/documentarray.js
  2. +20 −0 test/types.documentarray.test.js
View
@@ -64,18 +64,22 @@ MongooseDocumentArray.prototype._cast = function (value) {
*/
MongooseDocumentArray.prototype.id = function (id) {
+ var casted
+ , _id;
+
try {
- var casted = ObjectId.toString(ObjectIdSchema.prototype.cast.call({}, id));
+ casted = ObjectId.toString(ObjectIdSchema.prototype.cast.call({}, id));
} catch (e) {
- var casted = null;
+ casted = null;
}
for (var i = 0, l = this.length; i < l; i++) {
- if (!(this[i].get('_id') instanceof ObjectId)) {
- if (String(id) == this[i].get('_id').toString())
+ _id = this[i].get('_id');
+ if (!(_id instanceof ObjectId)) {
+ if (String(id) == _id)
return this[i];
} else {
- if (casted == this[i].get('_id').toString())
+ if (casted == _id)
return this[i];
}
}
@@ -103,6 +103,26 @@ module.exports = {
var a = new MongooseDocumentArray([sub3]);
a.id(id3).title.should.equal('rock-n-roll');
a.id(sub3._id).title.should.equal('rock-n-roll');
+
+ // test with no _id
+ var NoId = new Schema({
+ title: { type: String }
+ }, { noId: true });
+
+ var Subdocument = TestDoc(NoId);
+
+ var sub4 = new Subdocument();
+ sub4.title = 'rock-n-roll';
+
+ var a = new MongooseDocumentArray([sub4])
+ , threw = false;
+ try {
+ a.id('i better not throw');
+ } catch (err) {
+ threw = err;
+ }
+ threw.should.equal(false);
+
},
'inspect works with bad data': function () {

0 comments on commit 2385a92

Please sign in to comment.