简体   繁体   English

架构有引用时如何从 mongoose 获取完整数据

[英]How to get full data from mongoose when schema has reference

This is the schema.这是架构。 My frontend needs [content, name, email] at the same time.我的前端同时需要 [内容、姓名、电子邮件]。 How to get those three data and render to frontend at the same time?如何获取这三个数据并同时渲染到前端? Can you provide a sample JS code to do that?你能提供一个示例JS代码来做到这一点吗?

const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    }
});

const PostSchema = new mongoose.Schema({
    author: {
       type: Schema.Types.ObjectID, ref:'User'
    },
    content:{
        type: String
    }

});

Please try below code, you can use populate to get data from reference:请尝试以下代码,您可以使用 populate 从参考中获取数据:

post.find()
        .where("field")
        .in([criteria])
        
        .populate("author")
        .exec(function (e, posts) {
            if (e) {
                //do error handling here
            }
            if (posts) {
               return posts;
            }
        });

or create post model create author model或创建帖子 model 创建作者 model

 post.find()
        .where("field")
        .in([criteria])
        
        .populate({
            path: 'author',
            model: authorModel
            )}
        .exec(function (e, posts) {
            if (e) {
                //do error handling here
            }
            if (posts) {
               return posts;
            }
        });

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

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