Created
July 8, 2012 16:28
-
-
Save geta6/3071649 to your computer and use it in GitHub Desktop.
mongooseでschemaをネストする
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Schema = mongoose.Schema | |
ObjectId = Schema.ObjectId | |
# スキーマ定義 | |
PostSchema = new Schema | |
title: type: String, unique: true | |
content: String | |
author: type: ObjectId, ref: 'users' | |
comments: [ type: ObjectId, ref: 'comments' ] | |
created: type: Date, default: new Date.now() | |
CommentSchema = new Schema | |
owner: String | |
content: String | |
created: type: Date, default: new Date.now() | |
UserSchema = new Schema | |
name: type: String, unique: true | |
# modelを登録 | |
Post = mongoose.model 'posts', PostSchema | |
Comment = mongoose.model 'comments', CommentSchema | |
User = mongoose.model 'users', UserSchema | |
# データを作成する | |
User.findOne name: "geta6", (err, user) -> | |
if !err | |
second = new Post | |
title: "my second post" | |
content: "this is my second post." | |
author: user._id | |
second.save() | |
# データを読む | |
Post.findOne( title: "my first post") | |
.populate("author") | |
.populate("comments") | |
.exec (err, post) -> | |
if !err | |
console.log post | |
# データを追加する(commentを追加) | |
Post.findOne title: "my first post", (err, post) -> | |
if !err | |
comment = new Comment | |
owner: "anonymous" | |
content: "nice post!!" | |
comment.save() | |
post.comments.push comment._id | |
post.save() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment