猫鼬-空数组

时间:2018-10-23 19:59:59

标签: node.js mongodb mongoose

即使有两只类型为 dog 的动物,回调函数也会打印一个空数组。我究竟做错了什么?谢谢 :) 节点js应用程序如下所示:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true });

let db = mongoose.connection;

db.on('error', console.error.bind(console, 'an error occured'));

db.on('open', function () {
    let animalSchema = new Schema({ name: String, type: String });

    animalSchema.methods.findSimilarTypes = function (cb) {
        return this.model('animal').find({ type: this.type }, cb);
    };

    const animal = mongoose.model('animal', animalSchema, 'animal');
    let dog = new animal({ type: 'dog', name: 'doggy' });
    let cat = new animal({ type: 'cat', name: 'catty' });
    let yono = new animal({ type: 'dog', name: 'dini' });

    dog.findSimilarTypes(function (err, dogs) {
        console.log('dogs', dogs); 
    });
});

1 个答案:

答案 0 :(得分:0)

您创建了新动物,但没有将它们保存到数据库中

let dog = new animal({ type: 'dog', name: 'doggy' }).save();
let cat = new animal({ type: 'cat', name: 'catty' }).save();
let yono = new animal({ type: 'dog', name: 'dini' }).save();

如果您仍然得到一个空数组,那么可以通过使用async/await并在我们继续执行代码之前等待所有文档被保存来解决某些竞速条件

// Make our callback async function
db.on('open', async function () {
  let animalSchema = new Schema({ name: String, type: String });

  animalSchema.methods.findSimilarTypes = function (cb) {
    return this.model('animal').find({ type: this.type }, cb);
  };

  const animal = mongoose.model('animal', animalSchema, 'animal');
  let dog = new animal({ type: 'dog', name: 'doggy' });
  let cat = new animal({ type: 'cat', name: 'catty' });
  let yono = new animal({ type: 'dog', name: 'dini' });

  // Wait for our database to finish saving all of our animals
  await Promise.all([
    dog.save(),
    cat.save(),
    yono.save()
  ]);

  dog.findSimilarTypes(function (err, dogs) {
    console.log('dogs', dogs); 
  });
});