美文网首页
模型之中嵌套自定义属性

模型之中嵌套自定义属性

作者: 黑山老水 | 来源:发表于2017-09-19 11:28 被阅读22次

    为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();
                });
             });
    

    相关文章

      网友评论

          本文标题:模型之中嵌套自定义属性

          本文链接:https://www.haomeiwen.com/subject/smaisxtx.html