forked from Automattic/mongoose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtypes.documentarray.test.js
444 lines (375 loc) · 12.4 KB
/
types.documentarray.test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/**
* Module dependencies.
*/
var start = require('./common')
, mongoose = require('./common').mongoose
, random = require('../lib/utils').random
, setValue = require('../lib/utils').setValue
, MongooseArray = mongoose.Types.Array
, MongooseDocumentArray = mongoose.Types.DocumentArray
, EmbeddedDocument = require('../lib/types/embedded')
, DocumentArray = require('../lib/types/documentarray')
, Schema = mongoose.Schema
, ObjectId = Schema.ObjectId
, assert = require('assert')
, collection = 'types.documentarray_' + random()
/**
* Setup.
*/
function TestDoc (schema) {
var Subdocument = function () {
EmbeddedDocument.call(this, {}, new DocumentArray);
};
/**
* Inherits from EmbeddedDocument.
*/
Subdocument.prototype.__proto__ = EmbeddedDocument.prototype;
/**
* Set schema.
*/
var SubSchema = new Schema({
title: { type: String }
});
Subdocument.prototype.$__setSchema(schema || SubSchema);
return Subdocument;
}
/**
* Test.
*/
describe('types.documentarray', function(){
it('behaves and quacks like an array', function(done){
var a = new MongooseDocumentArray();
assert.ok(a instanceof Array);
assert.ok(a instanceof MongooseArray);
assert.ok(a instanceof MongooseDocumentArray);
assert.ok(Array.isArray(a));
assert.equal('Object', a._atomics.constructor.name);
assert.equal('object', typeof a);
var b = new MongooseArray([1,2,3,4]);
assert.equal('object', typeof b);
assert.equal(Object.keys(b.toObject()).length,4);
done();
});
it('#id', function(done){
var Subdocument = TestDoc();
var sub1 = new Subdocument();
sub1.title = 'Hello again to all my friends';
var id = sub1.id;
var a = new MongooseDocumentArray([sub1]);
assert.equal(a.id(id).title, 'Hello again to all my friends');
assert.equal(a.id(sub1._id).title, 'Hello again to all my friends');
// test with custom string _id
var Custom = new Schema({
title: { type: String }
, _id: { type: String, required: true }
});
var Subdocument = TestDoc(Custom);
var sub2 = new Subdocument();
sub2.title = 'together we can play some rock-n-roll';
sub2._id = 'a25';
var id2 = sub2.id;
var a = new MongooseDocumentArray([sub2]);
assert.equal(a.id(id2).title, 'together we can play some rock-n-roll');
assert.equal(a.id(sub2._id).title, 'together we can play some rock-n-roll');
// test with custom number _id
var CustNumber = new Schema({
title: { type: String }
, _id: { type: Number, required: true }
});
var Subdocument = TestDoc(CustNumber);
var sub3 = new Subdocument();
sub3.title = 'rock-n-roll';
sub3._id = 1995;
var id3 = sub3.id;
var a = new MongooseDocumentArray([sub3]);
assert.equal(a.id(id3).title, 'rock-n-roll');
assert.equal(a.id(sub3._id).title, '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;
}
assert.equal(false, threw);
// test the _id option, noId is deprecated
var NoId = new Schema({
title: { type: String }
}, { _id: false });
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;
}
assert.equal(false, threw);
// test when _id is a populated document
var Custom = new Schema({
title: { type: String }
});
var Custom1 = new Schema({}, { id: false });
var Subdocument = TestDoc(Custom);
var Subdocument1 = TestDoc(Custom1);
var sub = new Subdocument1();
var sub1 = new Subdocument1();
sub.title = 'Hello again to all my friends';
var id = sub1._id.toString();
setValue('_id', sub1 , sub);
var a = new MongooseDocumentArray([sub]);
assert.equal(a.id(id).title, 'Hello again to all my friends');
done();
})
describe('inspect', function(){
it('works with bad data', function(done){
var threw = false;
var a = new MongooseDocumentArray([null]);
try {
a.inspect();
} catch (err) {
threw = true;
console.error(err.stack);
}
assert.ok(!threw);
done();
})
})
describe('toObject', function(){
it('works with bad data', function(done){
var threw = false;
var a = new MongooseDocumentArray([null]);
try {
a.toObject();
} catch (err) {
threw = true;
console.error(err.stack);
}
assert.ok(!threw);
done();
})
it('passes options to its documents (gh-1415)', function(done){
var subSchema = new Schema({
title: { type: String }
});
subSchema.set('toObject', {
transform: function (doc, ret, options) {
// this should not be called because custom options are
// passed during MongooseArray#toObject() calls
ret.changed = 123;
return ret;
}
})
var db = mongoose.createConnection();
var M = db.model('gh-1415', { docs: [subSchema] });
var m = new M;
m.docs.push({ docs: [{ title: 'hello' }] });
var delta = m.$__delta()[1];
assert.equal(undefined, delta.$pushAll.docs[0].changed);
done();
})
it('uses the correct transform (gh-1412)', function(done){
var db = start();
var FirstSchema = new Schema({
second: [SecondSchema],
});
FirstSchema.set('toObject', {
transform: function first(doc, ret, options) {
ret.firstToObject = true;
return ret;
},
});
var SecondSchema = new Schema({});
SecondSchema.set('toObject', {
transform: function second(doc, ret, options) {
ret.secondToObject = true;
return ret;
},
});
var First = db.model('first', FirstSchema);
var Second = db.model('second', SecondSchema);
var first = new First({
});
first.second.push(new Second());
first.second.push(new Second());
var obj = first.toObject();
assert.ok(obj.firstToObject);
assert.ok(obj.second[0].secondToObject);
assert.ok(obj.second[1].secondToObject);
assert.ok(!obj.second[0].firstToObject);
assert.ok(!obj.second[1].firstToObject);
done();
})
})
describe('create()', function(){
it('works', function(done){
var a = new MongooseDocumentArray([]);
assert.equal('function', typeof a.create);
var schema = new Schema({ docs: [new Schema({ name: 'string' })] });
var T = mongoose.model('embeddedDocument#create_test', schema, 'asdfasdfa'+ random());
var t = new T;
assert.equal('function', typeof t.docs.create);
var subdoc = t.docs.create({ name: 100 });
assert.ok(subdoc._id);
assert.equal(subdoc.name, '100');
assert.ok(subdoc instanceof EmbeddedDocument);
done();
})
})
describe('push()', function(){
it('does not re-cast instances of its embedded doc', function(done){
var db = start();
var child = new Schema({ name: String, date: Date });
child.pre('save', function (next) {
this.date = new Date;
next();
});
var schema = Schema({ children: [child] });
var M = db.model('embeddedDocArray-push-re-cast', schema, 'edarecast-'+random());
var m = new M;
m.save(function (err) {
assert.ifError(err);
M.findById(m._id, function (err, doc) {
assert.ifError(err);
var c = doc.children.create({ name: 'first' })
assert.equal(undefined, c.date);
doc.children.push(c);
assert.equal(undefined, c.date);
doc.save(function (err) {
assert.ifError(err);
assert.ok(doc.children[doc.children.length-1].date);
assert.equal(c.date, doc.children[doc.children.length-1].date);
doc.children.push(c);
doc.children.push(c);
doc.save(function (err) {
assert.ifError(err);
M.findById(m._id, function (err, doc) {
db.close()
assert.ifError(err);
assert.equal(3, doc.children.length);
doc.children.forEach(function (child) {
assert.equal(doc.children[0].id, child.id);
})
done();
})
})
})
})
})
})
it('corrects #ownerDocument() if value was created with array.create() (gh-1385)', function(done){
var mg = new mongoose.Mongoose;
var M = mg.model('1385', { docs: [{ name: String }] });
var m = new M;
var doc = m.docs.create({ name: 'test 1385' });
assert.notEqual(String(doc.ownerDocument()._id), String(m._id));
m.docs.push(doc);
assert.equal(doc.ownerDocument()._id, String(m._id));
done();
})
})
it('#push should work on EmbeddedDocuments more than 2 levels deep', function (done) {
var Comments = new Schema;
Comments.add({
title : String
, comments : [Comments]
});
var BlogPost = new Schema({
title : String
, comments : [Comments]
});
var db = start()
, Post = db.model('docarray-BlogPost', BlogPost, collection)
var p =new Post({ title: "comment nesting" });
var c1 = p.comments.create({ title: "c1" });
var c2 = p.comments.create({ title: "c2" });
var c3 = p.comments.create({ title: "c3" });
p.comments.push(c1);
c1.comments.push(c2);
c2.comments.push(c3);
p.save(function (err) {
assert.ifError(err);
Post.findById(p._id, function (err, p) {
assert.ifError(err);
var c4= p.comments.create({ title: "c4" });
p.comments[0].comments[0].comments[0].comments.push(c4);
p.save(function (err) {
assert.ifError(err);
Post.findById(p._id, function (err, p) {
db.close();
assert.ifError(err);
assert.equal(p.comments[0].comments[0].comments[0].comments[0].title, 'c4');
done();
});
});
});
})
});
describe('invalidate()', function(){
it('works', function(done){
var schema = Schema({ docs: [{ name: 'string' }] });
var T = mongoose.model('embeddedDocument#invalidate_test', schema, 'asdfasdfa'+ random());
var t = new T;
t.docs.push({ name: 100 });
var subdoc = t.docs[t.docs.length-1];
subdoc.invalidate('name', 'boo boo', '%');
subdoc = t.docs.create({ name: 'yep' });
assert.throws(function(){
// has no parent array
subdoc.invalidate('name', 'crap', 47);
}, /^Error: Unable to invalidate a subdocument/);
t.validate(function (err) {
var e = t.errors['docs.0.name'];
assert.ok(e);
assert.equal(e.path, 'docs.0.name');
assert.equal(e.type, 'user defined');
assert.equal(e.message, 'boo boo');
assert.equal(e.value, '%');
done();
})
})
it('handles validation failures', function(done){
var db = start();
var nested = Schema({ v: { type: Number, max: 30 }});
var schema = Schema({
docs: [nested]
}, { collection: 'embedded-invalidate-'+random() });
var M = db.model('embedded-invalidate', schema);
var m = new M({ docs: [{ v: 900 }] });
m.save(function (err) {
db.close();
assert.equal(900, err.errors['docs.0.v'].value);
done();
});
})
it('removes attached event listeners when creating new doc array', function(done) {
var db = start();
var nested = Schema({ v: { type: Number }});
var schema = Schema({
docs: [nested]
}, { collection: 'gh-2159' });
var M = db.model('gh-2159', schema);
M.create({ docs: [{v: 900}] }, function(error, m) {
m.shouldPrint = true;
assert.ifError(error);
var numListeners = m._events.save.length;
assert.ok(numListeners > 0);
m.docs = [{ v: 9000 }];
m.save(function(error, m) {
assert.ifError(error);
assert.equal(numListeners, m._events.save.length);
done();
});
});
});
})
})