我试图从一个名为“fruitDB”的数据库中检索特定字段,而我试图检索的表是从“fruits”表中检索的。到目前为止,我可以使用猫鼬从“水果”表中检索文档的所有字段。
我想要的是从该表中检索特定字段,而不是检索所有字段。我该怎么做?顺便说一句,我们不能再在最新的猫鼬版本中使用回调函数了。
以下是我迄今为止所做的尝试,
import mongoose, { mongo } from "mongoose";
mongoose.connect("mongodb://localhost:27017/fruitsDB");
const fruitSchema = new mongoose.Schema({
name: String,
rating: Number,
review: String,
});
const Fruit = mongoose.model("Fruit", fruitSchema);
const fruit = new Fruit({
name: "Apple",
rating: 7,
review: "Pretty solid as a fruit.",
});
const kiwi = new Fruit({
name: "Kiwi",
score: 10,
review: "The best fruit!",
});
const orange = new Fruit({
name: "Orange",
score: 4,
review: "Too sour for me",
});
const banana = new Fruit({
name: "Banana",
score: 3,
review: "Weird texture",
});
try {
for await (const fruitAll of Fruit.find()) {
console.log(fruitAll);
}
} catch (error) {
console.log(error);
}
在上面的代码中,它将显示所有项目和所有字段。
我尝试使用下面的代码来获取带有名称的字段,但我收到一个错误,说不再支持回调函数。
Fruit.find(function(err, fruits) {
if(err) {
console.log(err);
} else {
fruits.forEach(function(fruit){
console.log(fruit.name);
});
}
});
如果你有什么建议,如果有比Mongoose更好的ODM,请随意提及。我仍然是Mongoose和mongoDB的新手。