我是mongoose的新手,在我的代码中,我只创建了一个水果模式并在其中插入了一些文档,然后我只运行mongose.find((函数来读取控制台内的元素,一切都很好,但当我最后使用mongose.connection.close((函数时,它显示了错误,而当find((函数内部使用相同的mongoose.connection.colose(( 控制台中显示错误无法读取未定义的的属性"forEach"> 但是当我在find((函数中使用close((时,它运行得很好,没有任何错误如下所示 不知道这里出了什么问题,有人能帮忙解决吗。提前谢谢。const mongoose = require("mongoose");
mongoose.pluralize(null);
mongoose.connect("mongodb://localhost:27017/fruitsDB", { useUnifiedTopology: true, useNewUrlParser: true });
const fruitSchema = new mongoose.Schema({
name: String,
rating: {
type: Number,
min: 1,
max: 10
},
review: String
});
const Fruit = mongoose.model("Fruit", fruitSchema);
const fruit = new Fruit({
name: "black",
rating: 7,
// review: "Pretty solid as a fruit."
});
fruit.save();
Fruit.find(function(err, elements){
elements.forEach(function(e,i){
console.log(e.name, i);
});
});
mongoose.connection.close();
Fruit.find(function(err, elements){
mongoose.connection.close();
elements.forEach(function(e,i){
console.log(e.name, i);
});
});
尝试执行以下操作:
let elements = await Fruit.find();
elements.forEach(function(e,i){
console.log(e.name, i);
});
mongoose.connection.close();
您应该在其他mongoose
函数调用(如save
(中也使用await
,以获得正确的同步