繁体   English   中英

使用 Mongoose 中另一个 model 的属性查找一个 model 中的所有文档

[英]Find all documents in one model using property of another model in Mongoose

我有两个名为 post 和 user 的模型。 Post Model定义如下:

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: []
    }
});

用户model定义如下:

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: []
    }
});

我需要获取所有具有类似于用户标签的标签的帖子。 这意味着如果用户标签有 tag-1 和 tag-2,我需要所有有 tag-1 和 tag-2 的帖子,或者只有 tag-1 或 tag-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];
        });
    }

我只是想知道是否有更好的方法来获取所有具有用户标签的帖子。

不确定为什么要将用户标签推送到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语法。 使用一个而不是两个

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM