如果没有数据库部分,您通常会在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函数,但似乎它们没有做我需要的东西。 (或者我只是没有得到它)
我认为这很简单,我忽视了显而易见的事情,所以请指出正确的方向。非常感谢!
答案 0 :(得分: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]
}