mongodb Dog.find() 在 Dog.create() 之前执行

mongodb Dog.find() is executing before Dog.create()

mongodb Dog.find() 在 Dog.create()

之前执行

我只是有一些问题,我不明白为什么会这样。 我刚开始学习 mongodb 在线 tutorial.I 在 cloud9 练习我的代码。 我正在练习基本查询,例如 find() 和 create()。 我首先添加了 Dog.create() 方法,方法是添加一个只有名称参数的新狗,然后在 create() 方法下方添加了 Dog.find() 以查找数据库中存在的所有数据。

但问题是Dog.find()先执行,Dog.create最后执行。

我已经发布了下面的代码。

var mongoose= require("mongoose");
mongoose.connect("mongodb://localhost/dog_app");

var dogSchema = new mongoose.Schema({
  name:String
});

var Dog = mongoose.model("Dog", dogSchema);

Dog.create({
    name:"duppy"
}, function(err, dog){
    if(err){
        console.log(err);
    }else{
        console.log("created a new dog");
        console.log(dog);
    }
});

Dog.find({}, function(err , dogs){
   if(err){
       console.log(err);
   } else{
       console.log("retrived from database");
       console.log(dogs);
   }
});

结果

adi188288:~/workspace/IntroToNode/Databases $ node dogs.js
(node:7113) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/connections.html#use-mongo-client
retrived from database
[ { _id: 59bd6256bffba3198bce7e87, name: 'Puppy', __v: 0 } ]
created a new dog
{ __v: 0, name: 'Puppy2', _id: 59bd6932a2d4c81bc9488b74 }

您可以看到首先执行 find 方法然后执行 create 方法的结果 occurs.Can有人给我解释一下吗?

您已经创建了竞争条件。这两个调用都是异步的,这意味着它们不会立即 return,它们必须等待数据库完成其操作。但是,您通过在同一个时钟周期内执行这两个调用来并行执行。

基本上您的代码向 MongoDB 发送了两个请求;一个是它创造了一只狗,另一个是寻找狗。 MongoDB 并行处理两者,并发回两者的结果。在这种情况下 find 调用花费的时间较少,因此它首先调用它的回调。

如果你想让一个在另一个之后执行,你必须把它们放在回调中。只有在异步操作完成后才会调用回调:

Dog.create({
    name:"duppy"
}, function(err, dog){
    if(err){
        console.log(err);
    }else{
        console.log("created a new dog");
        console.log(dog);

        Dog.find({}, function(err , dogs){
           if(err){
               console.log(err);
           } else{
               console.log("retrived from database");
               console.log(dogs);
           }
        });
    }
});

您可能还想按照 alexmac 的建议使用 promises:

Dog.create({
    name:"duppy"
}).then(function(dog){
  console.log("created a new dog");
  console.log(dog);
  return Dog.find({});
}).then(function(dogs){
  console.log("retrived from database");
  console.log(dogs);
});

或者您甚至可以使用 async/await