[英]Populating Object from Mongoose in Node.js
如果没有数据库部分,通常会在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函数,但似乎它们没有执行我需要的操作。 (或者我只是不明白)
我认为这很简单,并且我忽略了显而易见的内容,因此请为我指出正确的方向。 非常感谢!
我不知道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]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.