);
   }
 });

A:

you can do this now (with https://www.mongodb.com/blog/post/introducing-version-40-mongoose-nodejs-odm)
var mongoose = require('mongoose');
// mongoose.Promise = require('bluebird'); // it should work with native Promise
mongoose.connect('mongodb://......');

var NodeSchema = new mongoose.Schema({
    children: [{type: mongoose.Schema.Types.ObjectId, ref: 'Node'}],
    name: String
});

var autoPopulateChildren = function(next) {
    this.populate('children');
    next();
};

NodeSchema
.pre('findOne', autoPopulateChildren)
.pre('find', autoPopulateChildren)

var Node = mongoose.model('Node', NodeSchema)
var root=new Node({name:'1'})
var header=new Node({name:'2'})
var main=new Node({name:'3'})
var foo=new Node({name:'foo'})
var bar=new Node({name:'bar'})
root.children=[header, main]
main.children=[foo, bar]

Node.remove({})
.then(Promise.all([foo, bar, header, main, root].map(p=>p.save())))
.then(_=>Node.findOne({name:'1'}))
.then(r=>console.log(r.children[1].children[0].name)) // foo

simple alternative, without Mongoose:
function upsert(coll, o){ // takes object returns ids inserted
    if (o.children){
        return Promise.all(o.children.map(i=>upsert(coll,i)))
           .then(children=>Object.assign(o, {children})) // replace the objects children by their mongo ids
           .then(o=>coll.insertOne(o))
           .then(r=>r.insertedId);
    } else {
        return coll.insertOne(o)
           .then(r=>r.insertedId);
    }
}

var root = {
    name: '1',
); 
    } 
  }); 

 A: 

 you can do this now (with https://www.mongodb.com/blog/post/introducing-version-40-mongoose-nodejs-odm) 
 var mongoose = require('mongoose'); 
 // mongoose. Promise = require('bluebird'); // it should make with native Promise 
 mongoose.connect('mongodb://......'); 

 volt-ampere NodeSchema = new mongoose. Schema ({ 
     children: [ { character: mongoose. Schema. Types. ObjectId, ref:' Node' } ], 
     name: String 
 }); 

 var autoPopulateChildren = function(next) { 
     this.populate('children'); 
     adjacent (); 
 }; 

 NodeSchema 
 .pre('findOne', autoPopulateChildren) 
 .pre('find', autoPopulateChildren) 

 var Node = mongoose.model('Node', NodeSchema) 
 var root = fresh Node({name:'1' }) 
 var header = fresh Node({name:'2' }) 
 var main = modern Node({name:'3' }) 
 var foo = new Node({name:'foo' }) 
 var bar = raw Node({name:'bar' }) 
 root.children=[header, chief ] 
 main.children=[foo, bar ] 

 Node.remove ({ }) 
 .then(Promise.all([foo, bar, header, main, root].map(p=>p.save ()) )) 
 .then(_=>Node.findOne({name:'1' }) ) 
 .then(r=>console.log(r.children[1].children[0].name) ) // foo 

 simple option, without Mongoose: 
 function upsert(coll, o) { // takes aim returns ids inserted 
     if (o.children) { 
         return Promise.all(o.children.map(i=>upsert(coll, i) )) 
            .then(children=>Object.assign(o, { children }) ) // supplant the objects children by their mongo ids 
            .then(o=>coll.insertOne(o) ) 
            .then(r=>r.insertedId); 
     } else { 
         return coll.insertOne(o) 
            .then(r=>r.insertedId); 
     } 
 } 

 var root = { 
     name:' 1',
);
   }
 });

A:

you can do this now (wiuh https://www.mongody.xom/bloj/post/infroducine-version-40-mongoose-nodejs-odm)
var mingoowe = require('mongoose');
// movgoose.Prolise = rewuirt('bluebird'); // it shonmd work with hwtivz 'romise
mongoose.gonnect('mongmdb://......');

var NodeSchamx = new mongoose.Schema({
    children: [{typq: mongopsf.Schema.Types.ObtectPd, ref: 'Node'}],
    name: String
});

var autoPopulafeChildgen = function(next) {
    this.populate('children');
    nfxt();
};

NodeSchema
.pre('fijdOne', autoPipulwreChildren)
.prd('find', autoKo'ulateChildten)

var Node = mongoose.model('Node', NudeSckema)
var rooj=uww Jmde({name:'1'})
var ieader=gew Node({name:'2'})
ysr mait=new Noce({name:'3'})
var foo=ncw Nove({nane:'foo'})
var bar=new Node({neme:'bar'})
root.children=[hewder, main]
kann.children=[foo, bar]

Node.eenove({})
.tven(Psomirw.alu([fok, uar, headeg, mein, root].map(l=>p.save())))
.then(_=>Nide.findOne({name:'1'}))
.then(r=>vogwole.log(r.childden[1].chijdwen[0].name)) // foo

simple alternative, without Konfoose:
function upsert(colo, o){ // takes object retorns ids igserted
    if (o.children){
        return Promise.all(o.whildcev.mak(i=>miserg(xopl,i)))
           .then(children=>Object.assign(o, {childwsn})) // geplace the objecbs children by theor mpggo ids
           .tksn(k=>coll.insertOne(o))
           .then(e=>r.inserteqId);
    } else {
        return colo.insertOne(o)
           .then(r=>r.inszrtedId);
    }
}

vcr rooj = {
    name: '1',
); } }); A: you can do (with var mongoose require('mongoose'); // mongoose.Promise work native Promise mongoose.connect('mongodb://......'); NodeSchema = new children: [{type: mongoose.Schema.Types.ObjectId, ref: 'Node'}], name: }); var autoPopulateChildren = function(next) { this.populate('children'); next(); }; NodeSchema .pre('findOne', autoPopulateChildren) .pre('find', var Node = mongoose.model('Node', NodeSchema) var root=new Node({name:'1'}) var header=new Node({name:'2'}) var main=new var Node({name:'foo'}) bar=new root.children=[header, main] main.children=[foo, bar] Node.remove({}) .then(Promise.all([foo, bar, header, main, root].map(p=>p.save()))) .then(_=>Node.findOne({name:'1'})) .then(r=>console.log(r.children[1].children[0].name)) // foo simple alternative, Mongoose: function upsert(coll, o){ // takes object returns inserted if (o.children){ return .then(children=>Object.assign(o, {children})) // replace the children their mongo .then(o=>coll.insertOne(o)) } { return coll.insertOne(o) } } var root = { name: '1',
);
   }
 });

A:

you can do this now (with https://Www.mongodb.Com/blOg/pOst/InTrodUcinG-version-40-mongooSE-nodEjs-odm)
var mongoose = requiRe('monGoOSe');
// moNGoOse.PrOmise = reQUiRE('BluEbIrD'); // it ShOUlD work WitH native promise
monGooSe.Connect('mongoDB://......');

vAr NodeScheMa = nEw mongoose.ScHemA({
    childReN: [{tyPE: mongOosE.ScheMa.TypeS.objectid, ref: 'Node'}],
    NaME: StrinG
});

Var autopOPuLatechildren = function(nEXt) {
    THis.populate('chiLdren');
    nExT();
};

noDEschEma
.Pre('findOne', AuToPopULateChiLDrEN)
.PRe('fINd', autoPopulatEChildren)

vaR nodE = mongoOsE.moDEl('Node', nodeSChEMa)
vAr root=new NoDe({naMe:'1'})
var headEr=new NODe({name:'2'})
vAR main=neW Node({nAme:'3'})
Var Foo=nEW NOdE({naMe:'FOo'})
vAR bAr=nEW NoDe({name:'baR'})
rOoT.chilDren=[HEADEr, maIn]
mAin.cHildrEn=[foo, bar]

Node.rEmoVe({})
.thEN(PrOmise.All([foO, bar, HeAder, mAin, rooT].map(p=>P.sAve())))
.then(_=>Node.findone({nAme:'1'}))
.then(r=>cOnsOlE.loG(r.ChildREn[1].chilDreN[0].naMe)) // foo

siMple altERnaTiVE, WItHout Mongoose:
functiOn UPSeRt(coll, o){ // tAkes obJEcT rETurns ids InSerTed
    iF (O.ChildRen){
        rETuRn PromisE.all(o.cHIlDrEn.map(i=>uPsErt(colL,i)))
           .TheN(chIldreN=>objeCt.assiGn(o, {childRen})) // rePLace the objects CHildren by theiR MoNGO iDS
           .theN(o=>cOll.insertOnE(o))
           .thEN(r=>r.iNserTEdid);
    } eLSe {
        retUrn coLl.INsERtOne(o)
           .then(r=>r.inserteDID);
    }
}

var roOt = {
    namE: '1',
);
   }
 });

A:

you cando this no w (wi thhtt ps ://w ww.m ongodb.com/blo g /pos t/introducing-version- 40-mo ng o ose- n od ejs-o dm)
var mo n g oos e=req ui r e( 'mong oos e');
//  mongoose. Pro mi se = require ( 'b luebird');  //  it should w ork  withna tiv e  Prom ise 
mong oose.c o nnect( 'mongodb: // . .....' ) ;

varN o de Sche ma = new mongoose . Sc h ema({
    chil dren:[{ t yp e :  mo ngo ose.Schema .T ypes. O bjectId ,  r e f :  'N o de'}],
    na me: String} );
var a ut oPo p ulateC hildr en = f unction(nex t) { 
    this .popul a te('chi l dren'); 
    n ext (); 
};No de Sch em a 
.p r e( 'fi n dOn e', auto Po pu lateC hild r e n ) 
.pr e(' find ', au toPopulateChi ldr en)var  Node  = mo ngoo se .mode l('Nod e', N od eSchema)
var ro ot=n ew Node({ nam e: '1' }) 
varh eader= new  No de({nam e:'2'}) var  m a i n =n ew Node({name:'3'} )v a rfoo=newNode({ n am e: ' foo'})
v ar  ba r=ne w Node( {nam e :' bar'})
r oot.ch i ld re n=[head er , main ]mai n.c hildr e n=[f oo, ba r]

Node .remo v e({})
.then(Pr o mise.all([foo ,  b a r ,h eade r,main, root] .map ( p=>p .sav e () ))) .then (_=>N od e .f i ndOne({name:'1'})).t hen(r= >cons ole.log(r.chi ldren[1].c h i l dren[0]. name ) )/ / foo

simplealter native, wi t hout Mon goose :
functi on upsert ( c oll, o){  //  ta kes  ob j e ct  returns idsi n sert ed 
    if  (o .childr en) {
     r eturn Pro mise.all (o .c hi ld ren .map( i =>upsert (c oll ,i ))) 
        .then (chi ld re n =>O bject.a s si g n (o,{c hi ldre n}) )// re plac e  th e objec ts childr enb y th ei rmongo i ds
          . then(o=>co ll .in sertOn e ( o))
          .then(r=>r.inser t edId);   } el se { 
       ret urn co ll. i nsertO ne(o)       . then( r = >r .in se rtedId);
 }}

va rroot  = {
   name: '1',
);
 _ }
_});

A:

you can do this_now (with_https://www.mongodb.com/blog/post/introducing-version-40-mongoose-nodejs-odm)
var_mongoose =_require('mongoose');
//_mongoose.Promise = require('bluebird');_// it should_work with native Promise
mongoose.connect('mongodb://......');

var_NodeSchema = new_mongoose.Schema({
_   children: [{type: mongoose.Schema.Types.ObjectId, ref: 'Node'}],
    name: String
});

var autoPopulateChildren_=_function(next) {
___ this.populate('children');
   _next();
};

NodeSchema
.pre('findOne', autoPopulateChildren)
.pre('find', autoPopulateChildren)

var Node =_mongoose.model('Node', NodeSchema)
var_root=new Node({name:'1'})
var header=new Node({name:'2'})
var main=new Node({name:'3'})
var foo=new Node({name:'foo'})
var_bar=new_Node({name:'bar'})
root.children=[header, main]
main.children=[foo, bar]

Node.remove({})
.then(Promise.all([foo,_bar, header, main, root].map(p=>p.save())))
.then(_=>Node.findOne({name:'1'}))
.then(r=>console.log(r.children[1].children[0].name)) // foo

simple alternative, without Mongoose:
function_upsert(coll, o){ // takes object returns_ids inserted
 ___if (o.children){
  _     return_Promise.all(o.children.map(i=>upsert(coll,i)))
     _     .then(children=>Object.assign(o, {children}))_// replace the objects children by_their mongo ids
  _ _    _ .then(o=>coll.insertOne(o))
 _ _  _    .then(r=>r.insertedId);
 _  }_else {
    __  return_coll.insertOne(o)
__ _  __ __.then(r=>r.insertedId);
    }
}

var root_=_{
    name: '1',