如何从这个对象数组中访问“name”和“ObjectId”?(Mongoose,MongoDB)

4ktjp1zp  于 2022-11-03  发布在  Go
关注(0)|答案(2)|浏览(146)

我想访问name属性。我尝试执行以下操作,但它返回了undefined

Category.find()
    .select("-_id")
    .select("-__v")
    .then((categories) => {
      let creator = req.userId;
      console.log(categories.name) //undefined
      if (categories.creator === creator && categories.name === categoryName) {
        note
          .save()

这是console.log(categories)

[
  { name: 'test11', creator: new ObjectId("6359766eaf27f731e789f061") },
  { name: 'test11', creator: new ObjectId("6359766eaf27f731e789f061") },
  { name: 'categ1', creator: new ObjectId("635a316453d25ea50a3a4c5c") },
  { name: 'categ1', creator: new ObjectId("635a316453d25ea50a3a4c5c") },
  { name: 'categ1', creator: new ObjectId("635a316453d25ea50a3a4c5c") },
  { name: 'categ1', creator: new ObjectId("635a316453d25ea50a3a4c5c") },
  { name: 'categ1', creator: new ObjectId("635a316453d25ea50a3a4c5c") },
  {
    name: 'newCategName',
    creator: new ObjectId("635a316453d25ea50a3a4c5c")
  }
]

我想检查当前登录用户的ID和文档名是否与Category架构中的一对完全匹配

bz4sfanl

bz4sfanl1#

这里的Categories是一个对象数组,其中包含name和ObjectId。
所以只要循环遍历数组就可以得到你想要的结果。在代码中我看到你是这样做的:

console.log(categories.name)

请尝试:

console.log(categories[0].name)
zujrkrfu

zujrkrfu2#

因为返回的类别是一个对象列表而不是单个对象。您可以使用Array.find()来筛选条件。

var categories = [
  { name: "test11", creator: new ObjectId("6359766eaf27f731e789f061") },
  { name: "test11", creator: new ObjectId("6359766eaf27f731e789f061") },
  { name: "categ1", creator: new ObjectId("635a316453d25ea50a3a4c5c") },
  { name: "categ1", creator: new ObjectId("635a316453d25ea50a3a4c5c") },
  { name: "categ1", creator: new ObjectId("635a316453d25ea50a3a4c5c") },
  { name: "categ1", creator: new ObjectId("635a316453d25ea50a3a4c5c") },
  { name: "categ1", creator: new ObjectId("635a316453d25ea50a3a4c5c") },
  {
    name: "newCategName",
    creator: new ObjectId("635a316453d25ea50a3a4c5c"),
  },
];

const found = categories.find(
  (doc) => doc.creator === creator && doc.name === categoryName
);

if (found) {
  // rest of the code
}

尽管基于用例的更好和更有效的方法是直接在查询本身中使用筛选条件,而不是获取所有类别然后进行筛选。

const creator = req.userId;
const categoryName = "ABC";
const result = await Category.findOne(
  { creator: creator, name: categoryName },
  "-_id -__v"
).exec();

if (result) {
  // rest fo the code
}

使用findOne()和第二个参数投影来获得匹配类别。

相关问题