我有兩個名為 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: []
}
});
我需要獲取所有標簽類似于用戶標簽的帖子。這意味著如果用戶標簽具有標簽 1 和標簽 2,我需要所有具有標簽 1 和標簽 2 或僅標簽 1 或標簽 2 的帖子。目前,我正在做如下。
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];
});
}
我只是想知道是否有更好的方法來獲取所有具有用戶標簽的帖子。
uj5u.com熱心網友回復:
不確定為什么要將用戶標簽推送到tagsInfo陣列。但你能做到嗎
let user = await User.findById(req.body.userId);
您可以使用$in運算子來避免第二個回圈。如果需要,您可以if檢查(我假設findById回傳值)。
let Post = await Post.find({
tags: {
"$in": user.tags
}
});
如果您這樣做async/await,請不要使用then/catch語法。使用一個而不是兩個
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/459817.html
