deno.land / x / mongoose@6.7.5 / test / docs / schemas.test.js

schemas.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
'use strict';
const assert = require('assert');const mongoose = require('../../');const start = require('../common');
describe('Advanced Schemas', function() { let db; const Schema = mongoose.Schema;
before(function() { db = mongoose.createConnection(start.uri); });
after(async function() { await db.close(); });
/** * Mongoose allows creating schemas from [ES6 classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes). * The `loadClass()` function lets you pull in methods, * statics, and virtuals from an ES6 class. A class method maps to a schema * method, a static method maps to a schema static, and getters/setters map * to virtuals. */ it('Creating from ES6 Classes Using `loadClass()`', async function() { const schema = new Schema({ firstName: String, lastName: String });
class HumanClass { get fullName() { return 'My name'; } }
class PersonClass extends HumanClass { // `fullName` becomes a virtual get fullName() { return `${super.fullName} is ${this.firstName} ${this.lastName}`; }
set fullName(v) { const firstSpace = v.indexOf(' '); this.firstName = v.split(' ')[0]; this.lastName = firstSpace === -1 ? '' : v.substring(firstSpace + 1); }
// `getFullName()` becomes a document method getFullName() { return `${this.firstName} ${this.lastName}`; }
// `findByFullName()` becomes a static static findByFullName(name) { const firstSpace = name.indexOf(' '); const firstName = name.split(' ')[0]; const lastName = firstSpace === -1 ? '' : name.substring(firstSpace + 1); return this.findOne({ firstName, lastName }); } }
schema.loadClass(PersonClass); const Person = db.model('Person', schema); const doc = await Person.create({ firstName: 'Jon', lastName: 'Snow' });
assert.equal(doc.fullName, 'My name is Jon Snow'); doc.fullName = 'Jon Stark'; assert.equal(doc.firstName, 'Jon'); assert.equal(doc.lastName, 'Stark'); const foundPerson = await Person.findByFullName('Jon Snow'); assert.equal(foundPerson.fullName, 'My name is Jon Snow'); });});
mongoose

Version Info

Tagged at
a year ago