Listing 16.2 implements a schema on the word_stats
collection defined in Chapter 15, “Accessing MongoDB Documents from Node.js.” This schema will be used in other examples in this chapter, so it is exported in the final line of Listing 16.2. Notice that the word
and first
fields have an index
assigned to them and that the word
field is both unique
and required
.
For the stats
subdocument, the document is defined as normal but with types specified in lines 9–11. Also notice that for the charsets
field, which is an array of subdocuments, the syntax defines an array and defines the single subdocument type for the model. Lines 13–15 implement a startsWith()
method that is available on Document
objects in the model. Figure 16.2 shows the output of the required paths and indexes.
01 var mongoose = require('mongoose'),
02 var Schema = mongoose.Schema;
03 var wordSchema = new Schema({
04 word: {type: String, index: 1, required:true, unique: true},
05 first: {type: String, index: 1},
06 last: String,
07 size: Number,
08 letters: [String],
09 stats: {
10 vowels:Number, consonants:Number},
11 charsets: [{ type: String, chars: [String]}]
12 }, {collection: 'word_stats'});
13 wordSchema.methods.startsWith = function(letter){
14 return this.first === letter;
15 };
16 exports.wordSchema = wordSchema;
17 console.log("Required Paths: ");
18 console.log(wordSchema.requiredPaths());
19 console.log("Indexes: ");
20 console.log(wordSchema.indexes());