简体   繁体   English

pre save hook:猫鼬中的回调顺序如何

[英]pre save hook: how is the sequence of callbacks in mongoose

I would like to increment a counter in my pre save callback. 我想在预保存回调中增加一个计数器。 I found this stackoverflow really useful to do so: Does Mongoose support the Mongodb `findAndModify` method? 我发现此stackoverflow确实非常有用: Mongoose是否支持Mongodb的`findAndModify`方法?

What I would like to do is use the findAndModify method. 我想做的是使用findAndModify方法。 But when I implement the statics my squence of callbacks is not as expected. 但是,当我实现静态函数时,我的回调频率却不如预期。 I do always and pre save and then execute findAndModify but I would like do execute findAndModify in between start and end of the pre save hook. 我总是做并预先保存,然后执行findAndModify,但是我想在预先保存钩子的开始和结束之间执行findAndModify。 If I define a general method with a callback it works as expected. 如果我定义一个带有回调的通用方法,它将按预期工作。

worked also with the done parameter of the pre-save hook without any different result 也可以与预保存钩子的done参数一起使用,而没有任何不同的结果

What do I miss here 我在这里想念什么

My code looks like this: 我的代码如下所示:

var mongoose = require('mongoose');
var should = require('should');

mongoose.connect("localhost","test_db");

var CommentSchema = new mongoose.Schema({
  content:    {type:String},
  created_at: {type:Date, default:Date.now},
  _post:{type:mongoose.Schema.ObjectId,ref:'Post'}

});

var PostSchema = new mongoose.Schema({
  title:    {type:String},
  content:  {type:String},
  comments: [{type:mongoose.Schema.ObjectId, ref:'Comment'}],
  counter: {type:Number}

    });

PostSchema.statics.findAndModify= function(query,sort,doc,options,callback){
  return this.collection.findAndModify(query,sort,doc,options,callback);
 }

PostSchema.statics.test_me = function(clb){
   console.log("test_me");
   clb();
}
CommentSchema.pre('save',function(next,done){
  console.log("enter pre save comment");
  if(this.isNew){
   Post.findAndModify({_id:this._post},[],{$inc:{count:1}},{new:true},function(err,post){
    console.log("enter find-and-modify!");
    console.log(post);
   });
  Post.test_me(function(){
    console.log("callback of test_me");
  });
  console.log("exit pre save comment");

    next();
  }
});

var Post = mongoose.model('Post',PostSchema);
var Comment = mongoose.model('Comment',CommentSchema);

var post = new Post({title:"hello world"});
var comment = new Comment({content:"1st comment",_post:post});
post.comments.push(comment);

  var id = post.id;
  console.log(id);
  post.save(function(err){
    comment.save(function(err){
        Post.find({_id:id })
          .populate('comments')
          .exec(function(err,result){
          console.log("--------------- result -----------------");
          console.log(result);
          });
    });
  });

This is the result from my command-line: 这是我的命令行的结果:

5049f0d2e21547430a000001
enter pre save comment
test_me
callback of test_me
exit pre save comment
enter find-and-modify!
{ __v: 0,
  _id: 5049f0d2e21547430a000001,
  comments: [ 5049f0d2e21547430a000002 ],
  count: 1,
  title: 'hello world' }
--------------- result -----------------
[ { __v: 0,
    _id: 5049f0d2e21547430a000001,
    count: 1,
    title: 'hello world',
    comments: 
     [ { content: '1st comment',
         _post: 5049f0d2e21547430a000001,
         _id: 5049f0d2e21547430a000002,
         __v: 0,
         created_at: Fri Sep 07 2012 15:04:18 GMT+0200 (CEST) } ] } ]

EDIT: I do not want to know how to execute findAndModify with test_me in a sequence. 编辑:我不想知道如何在序列中用test_me执行findAndModify。 I want to know why findAndMody enters after pre-saved is finished. 我想知道为什么在预保存完成后进入findAndMody。 Even it is embedded and should work as demonstrated with the test_me method. 即使它是嵌入式的,也应该按照test_me方法演示的那样工作。 So the test_me method should illustrate that a async method should work nested... but findAndModify does not... like my command-line output shows...it always enters findAndModify after pre-save exits even when I use the done() callback... 因此,test_me方法应说明异步方法应嵌套使用...但是findAndModify不能...就像我的命令行输出所示...即使在我使用done()时,它也总是在预保存退出后进入findAndModify。打回来...

Since we are dealing with async, it will run 由于我们正在处理异步,它将运行

console.log("enter pre save comment");
if(this.isNew){
  Post.findAndModify({_id:this._post},[],{$inc:{count:1}},{new:true},function(err,post){
    console.log("enter find-and-modify!");
    console.log(post);
  });
  Post.test_me(function(){
    console.log("callback of test_me");
  });
  console.log("exit pre save comment");
  next();
}

one after the other, not waiting for it to execute or a response before moving on to the next. 一个接一个地执行,而不是等待它执行或响应,然后再继续执行下一个。 Since Post.findAndModify() takes longer to execute, anything in the callback function will execute after anything that is outside the callback function. 由于Post.findAndModify()需要更长的执行时间,因此回调函数中的所有内容都将在回调函数之外的任何内容之后执行。

If you want it to execute more in order 如果您希望它按顺序执行更多

console.log("enter pre save comment");
if(this.isNew){
  Post.findAndModify({_id:this._post},[],{$inc:{count:1}},{new:true},function(err,post){
    console.log("enter find-and-modify!");
    console.log(post);
    Post.test_me(function(){
      console.log("callback of test_me");
      console.log("exit pre save comment");
      next();
    });
  });     
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM