DEV Community

loading...

#13 Nesting Documents

rittwickbhabak profile image Rittwick Bhabak ・1 min read
const mongoose = require('mongoose');
const assert = require('assert')
const Author = require('../models/author');

describe('Nesting Documents', function(){

    //Create tests
    it('Create an author with sub-documents', function(done){

        var pat = new Author({
            name: 'Patrick Ruffus',
            books:[{title:'Name of the wind', pages: 400}]
        });
        pat.save().then(function(){
            Author.findOne({name:'Patrick Ruffus'}).then(function(record){
                assert(record.books.length === 1);
                done();
            })
        })
    })

    it('Add a book to an existing author', function(done){

        var rus = new Author({
            name: 'Ruskin Bond',
            books:[{title:'The eyes have it', pages: 400}]
        });
        rus.save().then(function(){
            Author.findOne({name:'Ruskin Bond'}).then(function(record){
                record.books.push({title:"7 husband", pages:200});
                record.save().then(function(){
                    Author.findOne({ name: 'Ruskin Bond' }).then(function(record){
                        assert(record.books.length===2);
                        done();
                    })
                })
            })
        })
    })
})
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide