Async virtual fields

1,691 views
Skip to first unread message

Zms

unread,
Jan 9, 2013, 5:32:32 AM1/9/13
to mongoo...@googlegroups.com
In my application, users will be able to change their names.
I want existing games to reflect this.

Current setup...

var PlayerSchema = new Schema({
    name: 'Foo',
    // ...
});


This example is working...

var PlayerSchema = new Schema({
    userid: ObjectId,
    // ...
});

PlayerSchema.virtual('name').get(function () {
    return 'Bar';
});

var GameSchema = new Schema({
    players: [PlayerSchema],
    // ...
}, { toJSON: { virtuals: true } });

module.exports.getGame = function (id, cb) {
    Game.findOne({ _id: id }, 'players', function (err, doc) {
        cb(doc);
    });
};

socket.on('getGame', function (id, fn) {
    db.getGame(id, function (game) {
        fn(game);
        // [{ _id: 5016bab0562cb81c6abe1811, name: 'Bar' }]
    });
});


Async getters does not...

PlayerSchema.virtual('name').get(function () {
    User.findOne({ _id: this.userid }, function (err, doc) {
        return doc.name;
    });
});


Is this the proper solution to this kind of scenario?
http://stackoverflow.com/questions/11981456/mongoose-getter-function-doesnt-return-updated-array-when-making-async-calls

Victor Powell

unread,
Jan 9, 2013, 5:24:24 PM1/9/13
to mongoo...@googlegroups.com
Virtuals only make sense for synchronous code. I would instead create a schema method. 

PlayerSchema.methods.getUser = function(cb){
  return User.findById(this.userid, cb)
}

then you can do

player.getUser(function(err, user){
  // access `user`
})

Thomas Häggkvist

unread,
Jan 10, 2013, 9:00:01 AM1/10/13
to mongoo...@googlegroups.com
I have come across this exact suggestion...

http://stackoverflow.com/questions/6077601/how-to-work-with-async-code-in-mongoose-virtual-properties

...but I don't get it. To me this looks just like adding a sub query + results manipulation + extra bloat.

Am I missing something? How to implement this in my given scenario?


2013/1/9 Victor Powell <vicapo...@gmail.com>
--
--
http://mongoosejs.com - docs
http://plugins.mongoosejs.com - plugins search
http://github.com/learnboost/mongoose - source code
 
You received this message because you are subscribed to the Google
Groups "Mongoose Node.JS ORM" group.
To post to this group, send email to mongoo...@googlegroups.com
To unsubscribe from this group, send email to
mongoose-orm...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/mongoose-orm?hl=en
 
 

Reply all
Reply to author
Forward
0 new messages