我正在使用Mongoose,Express和NodeJS实现一个审批系统。
每个岗位有2套批文。
我实现了如下模型:
Post Schema:
var PostSchema = new Schema({
UserId: { type: ObjectId, unique: true, default: null },
/..
.. Object related fields
../
Approval1: Object, //chidschema objects of approver
Approval2: Object
});
Approval Mapping Schema:
var ApprovalMapSchema = new Schema({
UserId: { type: ObjectId, unique: true, default: null },
Approver1Id: { type: ObjectId, default: null },
Approver2Id: { type: ObjectId, default: null }
});
我试图首先在我的函数中找到映射,然后在保存时更新主post对象。
我需要在保存新帖子之前检索两个审批者ID。
请提出一个好办法来做这件事。我目前正在做:
>
使用审批者条目更新Post对象。
post.save(function(err,doc){if(err){}else{console.log({success:true,msg:'successful created new post‘,content:doc});}});
/*var actId = activation._id, distributorId, ttlId;
var approvalMap = ApprovalMap.findOne({ userId: myUserId }, function(err, appMap) {
if (err) throw err;
else{
Approver1Id = appMap.Approver1Id;
Approver2Id = appMap.Approver2Id;
}
});
// Create child objects after this and update as subdocument
这对我不起作用。请救命!
我很难理解你的问题。但听起来您想要做这样的事情(您需要根据您想要做的事情对其进行修改,但希望它能向您展示一种处理异步行为的方法):
//This will run a query that returns a document where userId == myUserId
ApprovalMap.findOne({ userId: myUserId }, function(err, appMap) {
if (err) throw err;
//Once the query is complete function(err, appMap) will be called
//err will contain an error object if there was an error
//appMap will be the data returned by the query.
//within this block you can run another query
//for example
ApprovalMap.findOne({approved:'some variable'},function(err, secondQueryData){
if (err) throw err;
//after this query is complete function(err, secondQueryData) will be called
//once again the err argument will be an error, and the
//secondQueyrData argument will contain your return data
//here you can do something with the data
//for example, log the results
console.log(secondQueryData)
})
});
如您所见,可以在其他查询的回调中嵌套其他查询或步骤。这将确保事情以正确的顺序运行。您可能还想签出npm异步库,或者像q或Bluebird这样的promise库。他们也有一些很好的解决方案来处理Node中的异步行为。
根据@User2263572的建议,选择异步库。
我现在就是这样实现的:
async.waterfall(
[
function(callback){
ApprovalMap.findOne({ userId: myUserId }, function(err, appMap) {
if (err) throw err;
else{
//..Create child approval elements and assign Ids from map
callback(err, Approver1Child, Approver2Child);
}
});
},
function(Approver1Child, Approver2Child, callback){
var post = new Post(req.body);
post.distApproval = Approver1Child;
post.ttlApproval = Approver2Child;
post.userId = myUserId;
callback(null, post);
}
],
function(err, post){
//creating new order
post.save(function(err, doc) {
if (err) {
}
else
{
console.log({success: true, msg: 'Successful created new post', content: doc});
}
});
}
);
非常感谢@user2263572!!干杯!