node.js - 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;
解决方案
更好地使用 Mongoose 的内置populate()
方法,它可以让您引用其他集合中的文档,类似于$lookup
MongoDB 版本 >= 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'}, { ... }]
推荐阅读
- mysql - 如何给出一个以上的有子句
- c# - 如何将枚举字符串和值从 XML 模型解析为对象
- php - 引用的可打印 MIME 消息中的 CRLF
- pdf - 如何在 android-Webview 中加载 pdf?
- c# - 智能文件 API 上传文件
- python - 从基于类的表单 UpdateView django 中收集数据以在 views.py 中使用
- angularjs - 如何通过使用浏览器的刷新按钮或 Angular js 中的 CTRL+F5 来防止用户刷新页面的代码
- python - Python:在空格处拆分列表
- vba - 打开新工作簿 Excel 2016 VBA 后功能区无响应
- mysql - Spring Boot 连接到 MySQL 远程数据库