為user模型添加新的自定義的屬性
嵌套設計
- 每個user都有多篇post即user發布的文章
- 然而我們只創建post屬性的schema而不是創建一個新的model或collection,因為post屬性是屬于user的,而不是獨立存在于一個collection(這與傳統的關系數據庫有很大的區別)
- 在英語里如果我們將user成為document,那么我們定義的屬性post就是subdocument
創建新的屬性post
在src中創建post.js文件:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const PostSchema = new Schema({
title : String
});
module.exports = PostSchema;
并且在user model里面添加這個屬性:
//引用post屬性的schema
const PostSchema = require('./post');
//連接user模型和我們定義的屬性post
posts: [PostSchema]
測試
在test中添加subdocument_test.js文件:
const assert = require('assert');
const User = require('../src/user');
describe('Subdocuments', () => {
it('can create a subdocument', (done) => {
const Joe = new User({
name : 'Joe',
posts : [{title : 'PostTitle'}]
});
Joe.save()
.then(() => User.findOne({name : 'Joe'}))
.then((user) => {
assert(user.posts[0].title === 'PostTitle');
done();
});
});
});
使用復雜的回調嵌套來進行測試
測試流程
打開subdocument_test.js文件:
it('Can add subdocuments to an existing record', (done) => {
const Joe = new User({
name: 'Joe',
posts: []
});
Joe.save()
.then(() => User.findOne({name : 'Joe'})) //等于 () => {return User.findOne({name : 'Joe'})}
.then((user) => {
user.posts.push({title : 'New Post'}); //把新的記錄推送到user里面,此時這個instance并沒有在數據庫中更新
return user.save(); //在這里將修改過的記錄保存信息return出來
})
.then(() => User.findOne({name: 'Joe'})) //獲取上一個save函數里面最終的回調
.then((user) => {
assert(user.posts[0].title === 'New Post');
done();
});
});