我试图从名为“fruitDB”的数据库中检索特定字段,而我试图检索的表来自“fruits”表。到目前为止,我能够使用mongoose从“fruits”表中检索文档的所有字段。
我想要的是从该表中检索特定字段,而不是检索所有字段。我该怎么做?顺便说一句,我们不能在最新的mongoose版本中使用回调函数了。
这是我迄今为止所尝试的,
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);
});
}
});
如果你有任何建议,如果有更好的ODM比 Mongoose ,随时提出它。我还没有使用Mongoose和MongoDB。
2条答案
按热度按时间rjee0c151#
我刚刚发现它,当通过 Mongoose 文档。这是我在代码中调整的内容。
iyfjxgzm2#
您可以使用
select
方法仅选择希望在查询中返回的字段:参考docs。