[英]Return response from a module function node.js
I have an app file with routes in it and another module written which has the mongoose schema and the model object of a collection. 我有一个应用程序文件,其中包含路由,并且编写了另一个模块,其中包含猫鼬模式和集合的模型对象。 Code for app is:
该应用的代码为:
app.post("/saveNode", function(req, res) {
console.log(req.body.clientId)
if(req.body.hasOwnProperty("clientId")) {
defferedObject = nodeDbObject.returnCollectionObject(req.body);
}
}
From the route I am calling a function of mongoose model(returnCollectionObject)
object which will save the body
obtained in post call to the database.This function is written in the module. 从路由中,我正在调用猫鼬
model(returnCollectionObject)
对象的函数,该函数会将调用后获得的body
保存到数据库中。此函数编写在模块中。 Code for the same is given below: 相同的代码如下:
exports.returnCollectionObject = function(body) {
var collection = "refresh_hierarchy";
var nodeModelObject = mongoose.model(collection, folderSchema);
return nodeModelObject.create(body, function(err, resp) {
if(err == null) {
return resp;
}
});
};
I am calling this function from my route written for post. 我从写帖子的路线中调用此函数。 And i want the object returned from this
function(resp)
from inside my route so that i can use some of its fields to be returned in the response
. 而且我希望从我的路线内部从此
function(resp)
返回的对象,以便我可以使用其某些字段在response
返回。 Tried using .done()
on the defferedObject
but return resp
does not return anything. 在
defferedObject
上使用.done()
尝试过,但是return resp
不会返回任何内容。 Am i doing it right? 我做对了吗? Here is the code with done function.
这是完成功能的代码。
app.post("/saveNode", function(req, res) {
if(req.body.hasOwnProperty("clientId")) {
defferedObject = nodeDbObject.returnCollectionObject(req.body);
defferedObject.done(function(resp) {
res.send({"data": resp.uniqueNodeId, "error": err});
res.end();
});
}
}
This is just my first crack at writing a node service.Can Anyone help me out with this.Can it be done like that or not? 这只是我编写节点服务的第一步。任何人都可以帮我解决这个问题吗? The error i am getting is as below.
我得到的错误如下。
TypeError: Cannot call method 'done' of undefined
With async calls, returning value won't work, you need to use callbacks: 对于异步调用,返回值将不起作用,您需要使用回调:
exports.returnCollectionObject = function(body, callback) {
var collection = "refresh_hierarchy";
var nodeModelObject = mongoose.model(collection, folderSchema);
nodeModelObject.create(body, function(err, resp) {
callback(err, resp); // err might be null or some error, check in caller
});
};
In your route, do this: 在您的路线中,执行以下操作:
var dbObj = require('./nodeDbObject'); // assume you name file
// nodeDbObject.js which
// contains
// returnCollectionObject()
app.post("/saveNode", function(req, res) {
if(req.body.hasOwnProperty("clientId")) {
dbObj.returnCollectionObject(req.body, function(err, result) {
if (err) {
res.send({error: err});
} else {
res.send({data: result});
}
});
} else {
res.send({error: "no clientId"});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.