Populating Object from Mongoose in Node.js

Without the database part you normally create a new object in Javascript like this:

function object() {
    this.attribOne: 42,
    this.attribTwo: 'fourtytwo',

    [and so on creating more attribs and functions.]
};

Once this is done, you create a new "instance" of the object like this

var myObject = new object;

And myObject will have the correct attributes, functions.

Is there a way to do this if I need to load the attribute values from MongoDB using Mongoose (asynchronously)?

Similar to this?!

function object() {
    /* list of attributes */
    this.attribOne: null,
    this.attribTwo: null,

    function init(){
       // mongoose db call
       // set attributes based on the values from db
    }
};

I looked at the init functions but it seemed that they don't do what I need. (or I just didn't get it)

I assume this is simple and I am overlooking the obvious, so please point me to the right direction. Thanks a lot!

I don't know MongoDB, but you can pretty easily do what you want by passing in the database object you get back from the server into the constructor:

You can pass the object in like so:

var myObject = new object(MongoDBObj);

Then in your object Code you could do something like this:

function object(data) {

this.myProp1 = data.Prop1;//from db obj
this.myProp2 = data.Prop2;//from db obj

this.myProp3 = getProp3Calculation(); //from global calculation

[more functions and props for the object]

}

Edit: for my first comment

You can do this as well (simplistic example);

function object() {

this.myProp1 = null;
this.myProp2 = null;

this.myProp3 = getProp3Calculation(); //from global calculation

this.init = function([params]){
    var that = this;       


    var data = loadData(params);

    //if asynchronous the following code will go into your loadCompletedHandler
    //but be sure to reference "that" instead of "this" as "this" will have changed
    that.myProp1 = data.Prop1;
    that.myProp2 = data.Prop2;

};

[more functions and props for the object]

}

Update 3 - showing results of discussion below:

function object() {

this.myProp1 = null;
this.myProp2 = null;

this.myProp3 = getProp3Calculation(); //from global calculation

this.init = function([params], callback){
    var that = this;       



    var model = [Mongoose Schema];
    model.findOne({name: value}, function (error, document) {
        if (!error && document){

            //if asynchronous the following code will go into your loadCompletedHandler
            //but be sure to reference "that" instead of "this" as "this" will have changed
            that.myProp1 = document.Prop1;
            that.myProp2 = document.Prop2;

            callback(document, 'Success');


        }
        else{
            callback(null, 'Error retrieving document from DB');
    }
    });



};

[more functions and props for the object]

}