我使用mongodb和mongoose的promises时遇到了问题。 这是我的沙箱代码:
'use strict';
const mongoose = require('mongoose');
// Use JS native Promises to handle mongo promises
mongoose.Promise = Promise;
mongoose.connect("mongodb://localhost:27017/sandbox");
let db = mongoose.connection;
db.on('error', (err) => {
console.error(err);
});
db.once("open", () => {
console.log('Database connection successful');
// All database communication goes here
const AnimalSchema = new mongoose.Schema({
type: { type: String, default: "goldfish" },
size: { type: String, default: "small" },
color: { type: String, default: "golden" },
mass: { type: Number, default: 0.007 },
name: { type: String, default: "Angela" }
});
let Animal = mongoose.model('Animal', AnimalSchema);
let elephant = new Animal({
type: 'elephant',
size: 'big',
color: 'gray',
mass: 6000,
name: 'Lawrence'
});
let animal = new Animal({}); // Goldfish
let whale = new Animal({
type: 'whale',
size: 'big',
mass: 190500,
name: 'Fig'
});
Animal
.remove({})
.then(elephant.save())
.then(whale.save())
.then(animal.save())
// Find all big animals
.then(Animal.find({ size: 'big' }).exec())
// ERROR HERE
.then((err, animals) => {
animals.forEach(animal => console.log(`${animal.name} is ${animal.color} ${animal.type}`));
// console.log(err, animals);
})
.then(() => {
console.log('Saved!');
db.close().then(() => console.log('db connection closed'));
})
.catch((err) => {
console.error("Save Failed", err);
});
});
问题是,当我尝试在终端中执行此代码时,我收到错误:保存失败TypeError:无法读取属性' forEach'未定义的 在Animal.remove.then.then.then.then.then(C:_projects \ express_api \ mongoose_sandbox.js:54:11)
我的伐木活动有什么问题?