【发布时间】:2021-04-08 09:39:37
【问题描述】:
在猫鼬中,我建立了类似于猫鼬文档的关系,现在我想要一个对象数组
对象是我们拥有的对象的子对象
例如在 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 });
}
});
lives 有标题内容和作者(在 DB 中我将其命名为用户) 但是因为 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.js mongodb asynchronous mongoose foreach