0

データベース部分がなければ、通常は次のように Javascript で新しいオブジェクトを作成します。

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

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

これが完了したら、次のようにオブジェクトの新しい「インスタンス」を作成します

var myObject = new object;

そして、myObject は正しい属性、関数を持ちます。

Mongoose を使用して (非同期で) MongoDB から属性値をロードする必要がある場合、これを行う方法はありますか?

これに似てる?!

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

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

init 関数を見ましたが、必要なことをしていないようです。(または、私はそれを取得できませんでした)

これは単純だと思いますが、明らかなことを見落としているので、正しい方向に向けてください。どうもありがとう!

4

1 に答える 1

1

MongoDB についてはわかりませんが、サーバーから取得したデータベース オブジェクトをコンストラクターに渡すことで、必要なことを簡単に行うことができます。

次のようにオブジェクトを渡すことができます。

var myObject = new object(MongoDBObj);

次に、オブジェクトコードで次のようなことができます:

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]

}

編集:私の最初のコメント

これも同様に実行できます (単純な例)。

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]

}

更新 3 - 以下の議論の結果を表示:

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]

}
于 2012-08-16T15:37:00.097 に答える