2014년 12월 3일 수요일

[mongoose] Virtuals + Schemaless = undefined

I noticed that if I have the schema defined as Mixed {}, that virtuals won't work.

Schema


var ArtistSchema = mongoose.Schema({
       componists
: {} });


Object in MongoDB

{    _id:1928319237192387,    componists:      {         name: 'George Enescu'      } }

Mongoose Query

var find = function(req, res, next) {

 
return IP.findById(req.params.id, function(err, artist) {

 
if(!artist) {
     res
.status(404).send({
        status
: 'Not Found'
     
});
  
} else if (!err) {
     console
.log(JSON.stringify(artist.componists.name));
  
}
}


Output:

undefined

Expected Output:

George Enescu

However logging artist.componists works, giving back {name:'George Enescu'}



How are you defining your virtual? I don't see any virtuals here...



ArtistSchema.virtual('componists.familyName').get(function() {

    
return this.componists.split(' ')[1];
}




I'd recommend not using `.` in virtual names, there isn't much point, you'd have to access it with artist['componists.familyName'] because virtuals don't handle dots. Also, how are you using this virtual? Your original example doesn't use the virtual at all.


댓글 없음:

댓글 쓰기