使用 Mongoose 中另一个模型的 属性 查找一个模型中的所有文档
Find all documents in one model using property of another model in Mongoose
我有两个模型,分别名为 post 和 user。 Post 模型定义如下:
const postSchema = new mongoose.Schema({
_id: {
type: mongoose.Types.ObjectId,
auto: true,
},
userId: {
type: mongoose.Types.ObjectId,
required: true
},
header: {
type: String,
max: 1024,
required: true,
},
body: {
type: String,
},
tags: {
type: Array,
default: []
}
});
用户模型定义如下:
const userSchema = new mongoose.Schema({
_id: {
type: mongoose.Types.ObjectId,
auto: true,
},
username: {
type: String,
required: true,
max: 255,
},
email: {
type: String,
required: true,
max: 255,
},
password: {
type: String,
required: true,
min: 6,
max: 1024,
},
role: {
type: String,
required: true,
max: 255,
},
tags: {
type: Array,
default: []
}
});
我需要获取所有具有与用户标签相似的标签的 post。这意味着如果用户标签有 tag-1 和 tag-2,我需要所有有 tag-1 和 tag-2 或只有 tag-1 或 tag-2 的 post。目前我是这样做的。
tagsInfo = [];
await User.findById(req.body.userId).then((userInfo, err) => {
for (let i = 0; i < userInfo.tags.length; i++) {
tagsInfo.push(userInfo.tags[i]);
}
});
postsArray = [];
for (let i = 0; i < tagsInfo.length; i++) {
await Post.find({ tags: tagsInfo[i] }).then((posts, err) => {
postsArray = [...postsArray, posts];
});
}
我只是想知道是否有更好的方法来获取所有具有用户标签的 post。
不确定为什么要将用户标签推送到 tagsInfo
数组。但你能做到吗
let user = await User.findById(req.body.userId);
您可以使用 $in 运算符以避免第二次循环。如果需要,您可以输入 if
检查(我假设 findById
returns 值)。
let Post = await Post.find({
tags: {
"$in": user.tags
}
});
如果您正在做 async/await
,请不要使用 then/catch
语法。使用一个而不是两个
我有两个模型,分别名为 post 和 user。 Post 模型定义如下:
const postSchema = new mongoose.Schema({
_id: {
type: mongoose.Types.ObjectId,
auto: true,
},
userId: {
type: mongoose.Types.ObjectId,
required: true
},
header: {
type: String,
max: 1024,
required: true,
},
body: {
type: String,
},
tags: {
type: Array,
default: []
}
});
用户模型定义如下:
const userSchema = new mongoose.Schema({
_id: {
type: mongoose.Types.ObjectId,
auto: true,
},
username: {
type: String,
required: true,
max: 255,
},
email: {
type: String,
required: true,
max: 255,
},
password: {
type: String,
required: true,
min: 6,
max: 1024,
},
role: {
type: String,
required: true,
max: 255,
},
tags: {
type: Array,
default: []
}
});
我需要获取所有具有与用户标签相似的标签的 post。这意味着如果用户标签有 tag-1 和 tag-2,我需要所有有 tag-1 和 tag-2 或只有 tag-1 或 tag-2 的 post。目前我是这样做的。
tagsInfo = [];
await User.findById(req.body.userId).then((userInfo, err) => {
for (let i = 0; i < userInfo.tags.length; i++) {
tagsInfo.push(userInfo.tags[i]);
}
});
postsArray = [];
for (let i = 0; i < tagsInfo.length; i++) {
await Post.find({ tags: tagsInfo[i] }).then((posts, err) => {
postsArray = [...postsArray, posts];
});
}
我只是想知道是否有更好的方法来获取所有具有用户标签的 post。
不确定为什么要将用户标签推送到 tagsInfo
数组。但你能做到吗
let user = await User.findById(req.body.userId);
您可以使用 $in 运算符以避免第二次循环。如果需要,您可以输入 if
检查(我假设 findById
returns 值)。
let Post = await Post.find({
tags: {
"$in": user.tags
}
});
如果您正在做 async/await
,请不要使用 then/catch
语法。使用一个而不是两个