首页 > 解决方案 > nodejs中的异步foreach和mongoose

问题描述

在猫鼬中,我建立了像猫鼬文档这样的关系,现在我想获得一个对象数组

对象是我们拥有的对象的孩子

例如在 tweeter 中,一个用户有很多推文,每条推文都有标题、内容和作者

有人给我们用户ID,我们给他所有推文用户的标题和内容数组

[
{title: 'title01', content: 'aaaaaa'},
{title: 'title02', content: 'bbbbb'},
.
.
.
]

我试试

    const username = req.params.username;
    User.find({ username: username }, (err, docs) => {
      if (err) return res.json({ err: true });
      if (docs.length > 0) {
        let lives: Array<Object> = [];
        docs[0].lives.forEach((live, idx) => {
          Live.find({ _id: live }, (err, docs) => {
            lives.push(docs[0]);
          });
        });
      } else {
        return res.json({ err: true });
      }
    });

生活有标题内容和作者(在数据库中我将​​其命名为用户)但因为 aSync 我无法在 forEach 之后获得生活 :)

更新:

直播模式:

const schema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
  content: {
    type: String,
    required: true,
  },
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "users",
    required: true,
  },
});

用户架构:

import { ArraySortOptions } from "joi";
import mongoose, { Model } from "mongoose";

interface IUser extends mongoose.Document {
  email: string;
  username: string;
  password: string;
  lives: Array<mongoose.Schema.Types.ObjectId>;
}

const schema: mongoose.Schema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  lives: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "lives",
    },
  ],
});
const User: Model<IUser> = mongoose.model("users", schema);
export default User;

标签: node.jsmongodbasynchronousmongooseforeach

解决方案


更好地使用 Mongoose 的内置populate()方法,它可以让您引用其他集合中的文档,类似于$lookupMongoDB 版本 >= 3.2 中的类似联接的聚合运算符。

由于populate()需要一个查询来附加自身,因此用于User.findOne()查询与我们在参数中提供的用户名匹配的单个用户。

使用 async/await 可以按如下方式完成:

const { username } = req.params;
const user = await User.findOne({ username }).populate('lives');
console.log(user.lives); // ---> [{title: 'title01', content: 'aaaaaa'}, { ... }]

推荐阅读