2017-06-21 91 views
2

我有一个动物模式:猫鼬找到方法后,创建

const AnimalSchema = new mongoose.Schema({ 
    type: { type: String, default: "goldfish" }, 
    size: String, 
    color: { type: String, default: "golden" }, 
    mass: { type: Number, default: 0.007 }, 
    name: { type: String, default: "Angela" } 
}); 

动物实验数据数组:

let animalData = [ 
    { 
     type: 'mouse', 
     color: 'gray', 
     mass: 0.035, 
     name: 'Marvin' 
    }, 
    { 
     type: 'nutria', 
     color: 'brown', 
     mass: 6.35, 
     name: 'Gretchen' 
    }, 
    { 
     type: 'wolf', 
     color: 'gray', 
     mass: 45, 
     name: 'Iris' 
    } 
]; 

然后我试图清空在动物模型中的所有数据,保存阵列数据库,记录一些动物实验数据和关闭连接:

Animal 
    .remove({}) 
    .then(Animal.create(animalData)) 
    .then(Animal.find({}).exec()) 
    .then(animals => { 
     animals.forEach(animal => console.log(`${animal.name} is ${animal.color} ${animal.type}`)) 
    }) 
    .then(() => { 
     console.log('Saved!'); 
     db.close().then(() => console.log('db connection closed')); 
    }) 
    .catch((err) => { 
     console.error("Save Failed", err); 
    }); 

但是,当我试图执行此我得到一个错误: 保存失败类型错误:animals.forEach是不是Animal.remove.then.then.then.animals功能 (C:_projects \ express_api \ mongoose_sandbox.js:89:12)

这有什么错我的代码和如何使它工作?谢谢。

回答

2

好吧,这是一个简单的修复。 这是需要写我的。那么()方法:

Animal 
    .remove({}) 
    .then(Animal.create(animalData)) 
    .then(Animal.find({}).exec()) 

像:

Animal 
    .remove({}) 
    .then(() => Animal.create(animalData)) 
    .then(() => Animal.find({})) 

因此,在随后的方法是需要传递一个回调函数。