Now that the application is created, you need to also create the Page
and Photo
documents in the database. You can do this in several different ways. For example, you can add this ability directly to your application, which is a good way to go if you need it there later. Or you can use a JavaScript script directly in the MongoDB shell that includes the appropriate commands to create the documents. Or you can write a simple script in Node.js or some other language that supports accessing MongoDB.
Listing 27.19 shows a basic script that creates the Page
document and adds several Photo
documents as well. Each Page
and Photo
document also has a CommentThread
document created and associated with the commentId
reference.
01 var mongoose = require('mongoose'),
02 var db = mongoose.connect('mongodb://localhost/comments'),
03 require('./models/comments_model.js'),
04 require('./models/photo_model.js'),
05 require('./models/page_model.js'),
06 var CommentThread = mongoose.model('CommentThread'),
07 var Reply = mongoose.model('Reply'),
08 var Photo = mongoose.model('Photo'),
09 var Page = mongoose.model('Page'),
10 function addPhoto(title, filename){
11 var comment = new CommentThread({title: title +" Comments"});
12 comment.save(function(err, comment){
13 var photo = new Photo({title:title, filename:filename});
14 photo.commentId = comment.id;
15 photo.save(function(){
16 console.log(title + " Saved.");
17 });
18 });
19 }
20 CommentThread.remove().exec(function(){
21 Photo.remove().exec(function(){
22 Page.remove().exec(function(){
23 var comment = new CommentThread({title:"Photo Page Comments"});
24 comment.save(function(err, comment){
25 var page = new Page({name:"Photos Page"});
26 page.commentId = comment.id;
27 page.save();
28 });
29 addPhoto('Strength', 'arch.jpg'),
30 addPhoto('Power', 'pyramid.jpg'),
31 addPhoto('Beauty', 'flower.jpg'),
32 addPhoto('Thoughtful', 'boy.jpg'),
33 addPhoto('Summer Fun', 'boy2.jpg'),
34 addPhoto('Sunsets', 'jump.jpg'),
35 });
36 });
37 });;