首页 > 解决方案 > 对数组的 mongoose.model 索引返回未定义

问题描述

我在 mongoDB 中创建了一个简单的表(文档?)。我正在使用 Node 和 Mongoose 连接到它。

在我的方法中,我调用model.find({})以检索所有记录,然后遍历它们以找到我想要的记录(这是在一个循环中 - 我认为访问数据库一次,然后在内存中处理以避免每次都连接到数据库)。

当我console.log比赛时,我会打印出完整的对象。但是,当我打印出一个属性时,它会将其列为未定义。这个属性是一个数组,它发生在另一个属性中,它有一个我添加为测试的数组。我在这里想念什么?

这是我的代码片段:

 Documents.find({}).then(docsData => { // Documents is my model
      docs.entries.forEach(entry => { // docs.entries is the collection I want to match to
        const match = docsData.find(
          doc => doc['dropboxId'] == entry['id']
        );
        if (match) {

          entry['tags'] = match.tags;
          console.log('match tags', match.tags); // this prints out undefined
          console.log('match', match); // this prints out the object with tags
        }

有任何想法吗?

标签: javascriptnode.jsmongodbmongoose

解决方案


match是一个不同于普通 JS 对象的 Mongoose 文档。我想你需要这样做:

entry['tags'] = match.get('tags');


推荐阅读