Defining a valid mongoose schema for my JSON with nested docs without arrays? Defining a valid mongoose schema for my JSON with nested docs without arrays? mongoose mongoose

Defining a valid mongoose schema for my JSON with nested docs without arrays?


It looks like you are using mongoose embedded documents.

I'm not sure if embedded documents will always be wrapped inside arrays.

Following this mongoose documentation example :

var Comments = new Schema({    title     : String  , body      : String  , date      : Date});var BlogPost = new Schema({    author    : ObjectId  , title     : String  , body      : String  , date      : Date  , comments  : [Comments]  , meta      : {        votes : Number      , favs  : Number    }});

A BlogPost can contains severals Comments, and Comments will be wrapped inside an array (just like your issue if i'm right).

What if you get rid of that array in the schema definition ?

Using Comments instead of [Comments] :

var BlogPost = new Schema({    author    : ObjectId  , title     : String  , body      : String  , date      : Date  , comments  : Comments  , meta      : {        votes : Number      , favs  : Number    }});

I can't try that now.

Otherwise, I have an idea using mongoose virtual attributes, if this doesn't work, let me know.

Edit

Using virtual attributes, you could do something like this :

BlogPost    .virtual('customComment')    .get(function() {         return this.comments[0];     });

This will return the first Comment entry object whithout the array.

var BlogPost = mongoose.model('BlogPost');BlogPost    .find({ title: 'foo' })    .populate('comments')    .run(function (err, post) {    console.log(post.customComment); // returns the first comment without array});

Not tested, this may contains typos.