英文:
How to use forEach function in new version of Node.js too filter mongodb database
问题
尝试使用`.forEach`方法和`.find`方法从我的小数据库中仅显示汽车名称,但出现了错误
TypeError: Car.find(...).forEach is not a function
在此之前,尝试使用回调函数,但是MongoDB的新版本不再支持回调函数
我的整个代码在这里,只是尝试将Node.js应用程序连接到我的本地主机,并成功在控制台中显示了整个数据库,但在尝试仅显示汽车名称时卡住了
```js
const mongoose = require('mongoose');
const express = require('express');
const app = express();
mongoose.connect("mongodb://127.0.0.1:27017/carsDB", { useNewUrlParser: true, useUnifiedTopology: true });
const carSchema = new mongoose.Schema({
name: String,
year: Number,
make: String
});
const Car = mongoose.model("car", carSchema);
const elantra = new Car({
name: "Elantra",
year: 2020,
make: "Hyundai"
});
const civic = new Car({
name: "Civic Sport",
year: 2023,
make: "Honda"
});
Car.insertMany([elantra, civic]);
Car.find().forEach((car) => {
console.log(car.name);
});
Car.find().forEach((car) => {
console.log(car.name);
});
TypeError: Car.find(...).forEach is not a function
<details>
<summary>英文:</summary>
I try to display only name of cars from my small database by using .forEach method along with .find method but got error
TypeError: Car.find(...).forEach is not a function
Before this tried with call back function but newer version of mongodb doesn't support call back functionds any more
My whole is code is here just tried to connect nodejs app with my localhost and succesfully displayed the whole database in console but when tried to display only name of cars got stuck there
const mongoose = require('mongoose');
const express = require('express');
const app = express();
mongoose.connect("mongodb://127.0.0.1:27017/carsDB",{useNewUrlParser:true, useUnifiedTopology:true});
const carSchema = new mongoose.Schema({
name: String,
year: Number,
make:String
});
const Car = mongoose.model("car", carSchema);
const elantra = new Car({
name: "Elanta",
year: 2020,
make: "Hyundai"
});
const civic = new Car({
name: "Civic Sport",
year: 2023,
make: "Honda"
});
Car.insertMany([elantra,civic]);
Car.find().forEach((car)=>{
console.log(car.name);
});
Car.find().forEach((car)=>{
console.log(car.name);
`TypeError: Car.find(...).forEach is not a function`
</details>
# 答案1
**得分**: 0
尝试将exec()与find()一起使用:
```javascript
Car.find({}).exec()
.then(cars => {
cars.forEach(car => {
//...
})
})
.catch(err => console.error(err));
更多信息请参考:https://mongoosejs.com/docs/api/model.html#Model.find()
英文:
try putting the exec() with find():
Car.find({}).exec().
then( cars => {
cars.forEach( car => {
//...
})
}).
catch(err => console.error(err));
see more here: https://mongoosejs.com/docs/api/model.html#Model.find()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论