Mongoose 保存()在findOne()之前返回

lpwwtiir  于 2023-02-23  发布在  Go
关注(0)|答案(2)|浏览(144)

我正在使用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 }
});

我尝试先在函数中找到Map,然后在保存时更新主post对象。
我需要在保存新帖子之前检索两个批准人ID。
请建议一个好的方法去做它。我目前正在做:
1.使用Save //保存新Post对象在第2步后返回,我知道在Mongoose中异步保存,但我不希望在此之前调用第2步
1.使用ApprovalMapSchema上的findOne获取批准者ID
1.使用审批人条目更新Post对象。
post.save(函数(错误,文档){如果(错误){}否则{控制台.日志({成功:true,msg:'成功创建新公告',内容:文档}); } });

/*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

这对我没用,求你了救命!

i7uq4tfw

i7uq4tfw1#

我很难理解你的问题,但听起来你想做这样的事情(你需要根据你想做的事情修改它,但希望它能给你一种处理异步行为的方法):

//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 

            //secondQueryData argument will contain your return data
    
            //here you can do something with the data
            //for example, log the results

            console.log(secondQueryData)
        })
    });

正如您所看到的,您可以在其他查询的回调中嵌套额外的查询或步骤。这将确保事情以正确的顺序运行。您可能还想 checkout NPM异步库,或者像Q或Bluebird这样的Promise库。他们也有一些很棒的解决方案来处理Node中的异步行为。

ht4b089n

ht4b089n2#

根据@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!!干杯!

相关问题