deno.land / x / mongoose@6.7.5 / examples / schema / schema.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
/** * Module dependencies. */
'use strict';
const mongoose = require('../../lib');const Schema = mongoose.Schema;
/** * Schema definition */
// recursive embedded-document schema
const Comment = new Schema();
Comment.add({ title: { type: String, index: true }, date: Date, body: String, comments: [Comment]});
const BlogPost = new Schema({ title: { type: String, index: true }, slug: { type: String, lowercase: true, trim: true }, date: Date, buf: Buffer, comments: [Comment], creator: Schema.ObjectId});
const Person = new Schema({ name: { first: String, last: String }, email: { type: String, required: true, index: { unique: true, sparse: true } }, alive: Boolean});
/** * Accessing a specific schema type by key */
BlogPost.path('date') .default(function() { return new Date(); }) .set(function(v) { return v === 'now' ? new Date() : v; });
/** * Pre hook. */
BlogPost.pre('save', function(next, done) { /* global emailAuthor */ emailAuthor(done); // some async function next();});
/** * Methods */
BlogPost.methods.findCreator = function(callback) { return this.db.model('Person').findById(this.creator, callback);};
BlogPost.statics.findByTitle = function(title, callback) { return this.find({ title: title }, callback);};
BlogPost.methods.expressiveQuery = function(creator, date, callback) { return this.find('creator', creator).where('date').gte(date).run(callback);};
/** * Plugins */
function slugGenerator(options) { options = options || {}; const key = options.key || 'title';
return function slugGenerator(schema) { schema.path(key).set(function(v) { this.slug = v.toLowerCase().replace(/[^a-z0-9]/g, '').replace(/-+/g, ''); return v; }); };}
BlogPost.plugin(slugGenerator());
/** * Define model. */
mongoose.model('BlogPost', BlogPost);mongoose.model('Person', Person);
mongoose

Version Info

Tagged at
a year ago