2012-08-16 52 views
0

从猫鼬填充对象,而数据库的一部分,你通常在Javascript中创建一个新的对象是这样的:在Node.js的

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函数,但似乎他们没有做我所需要的。 (或我只是没有得到它)​​

我认为这很简单,我忽略了明显的,所以请指向正确的方向。非常感谢!

+0

我不知道我理解的问题。您从MongoDB查询中获得的文档已经是JavaScript对象。 – JohnnyHK 2012-08-16 15:18:04

+0

是的,这是真的,但我想填充一个对象,其中有没有存储在数据库中的其他属性和功能。例如:this.attribPlus = this.attribOne + this.attribTwo;或使用功能类似...我希望这是有道理的。 :) – 2012-08-16 15:22:28

回答

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] 

} 
+0

感谢您的回复。我知道这个选项,但这意味着,我有一个数据库调用“我的对象之外”。我希望将DB调用保存在对象中,最好是创建新对象时执行的函数。 例如:var myObject = new Object()。init([parameters]); 其中init()函数执行数据库调用并填充属性。 – 2012-08-16 15:41:09

+0

同样的想法。不要在创建时传递选项,只需激发对象的方法并从您从数据库中获取的值中加载对象属性。您可以使用“this”.property从函数引用对象的属性。我将在上面更新我的答案 – muck41 2012-08-16 15:45:54

+0

请在此处查看代码:http://pastebin.com/JjtJxrQG (回调不需要像那样传入。) 我可以访问并设置里面的“that”的值数据库调用? – 2012-08-16 15:59:17