Mongoose创build后find方法
我有一个动物模式:
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" } });
动物数据arrays:
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' } ];
然后我试图清空动物模型中的所有数据,将该数组保存到数据库,logging一些动物数据并closures连接:
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); });
但是当我试图执行这个,我得到一个错误:保存失败TypeError:animals.forEach不是在Animal.remove.then.then.then.animals(C:_projects \ express_api \ mongoose_sandbox.js: 89:12)
我的代码有什么问题,以及如何使其工作? 谢谢。
好的,这是一个简单的修复。 需要编写我的.then()方法:
Animal .remove({}) .then(Animal.create(animalData)) .then(Animal.find({}).exec())
喜欢:
Animal .remove({}) .then(() => Animal.create(animalData)) .then(() => Animal.find({}))
所以在那么方法是需要传递一个callback函数。