Quantcast
Channel: CNode:Node.js专业中文社区
Viewing all articles
Browse latest Browse all 14821

mongoose异步操作造成ctx.body不正常,求解决

$
0
0
  var username = ctx.session.current_user.username;
  var oldAccount = "";
  var account = {
    thing: ctx.request.body.thing,
    date: ctx.request.body.date,
    status: ctx.request.body.status,
    money: ctx.request.body.money
  };
  var resBody={};
  await UserModel.findByUsername(username, function (err, doc) {
    if (doc) {
      oldAccount = doc.accounts;
      oldAccount.push(account);
    } else {
      console.log(err);
      resBody = {
        type: "fail",
        message: "please check out your login status or input"
      }
    }
    return resBody;
  })
   UserModel.addAccount(username, oldAccount, function (err, doc) {
    if (doc) {
      resBody = {
        type: "success",
        message: "input success"
      }
      console.log(resBody)

    }
    else {
      console.log(err);
      resBody = {
        type: "fail",
        message: "please check out your login status or input"
      }
    }
  });
  ctx.body = resBody
  //ctx.body="上面数据库操作是能进行 但是由于异步问题   我实在无法解决 ctx.body ={}";

});```
下面是上面那2个函数

UserSchema.statics.findByUsername = function (username, cb) { return this.findOne({username: username}, cb); }

UserSchema.statics.addAccount = function(username,account,cb){ return this.findOneAndUpdate({username:username},{“accounts”:account},cb); }```


Viewing all articles
Browse latest Browse all 14821

Trending Articles