如何在NodeJS中使用Model.find()函数时使用mongoose检索特定字段

gdx19jrr  于 12个月前  发布在  Go
关注(0)|答案(2)|浏览(83)

我试图从名为“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。

rjee0c15

rjee0c151#

我刚刚发现它,当通过 Mongoose 文档。这是我在代码中调整的内容。

try {
  for await (const fruitAll of Fruit.find({}, 'name')) {
    console.log(fruitAll.name);
  }
} catch (error) {
  console.log(error);
}
iyfjxgzm

iyfjxgzm2#

您可以使用select方法仅选择希望在查询中返回的字段:

const fruits = await Fruit.find({}).select('name');
console.log(fruits);

参考docs

相关问题