简体   繁体   中英

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?

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:

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

 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;
            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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