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 回答