Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

mongoose - How to merge two schemas in mongodb

I have a post schema and user schema and I want to merge them together. I waant to know how to do it. So far I have this code but I keep returning promises. When I add then after the .map, I get no result. Any help would be appreciated

let posts = await Post.find();
            console.log(posts);
            let test = await posts.map(async(post) => {
                const creator = await User.findOne({token: post.creator});
                var username = null;
                if(creator){
                    username = creator.username;
                }

                return {...post._doc, username: username};
            });
            return posts;
question from:https://stackoverflow.com/questions/65839707/how-to-merge-two-schemas-in-mongodb

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can use q and async module

const q = require("q");
const async = require("async");

async function mainFunction() {
  try {
    let posts = await Post.find();
    let result = await getUser(posts);
    console.log(result)
  } catch (error) {
    console.error(error);
    return { error: error };
  }
}

async function getUser (posts) {
  let defer = q.defer;
  let test = [];
  async.eachSeries(posts,async (post) => {// like loop
      try {
        let creator = await User.findOne({ token: post.creator });
        var username = null;
        if (creator) {
          username = creator.username;
        }
        test.push({ ...post._doc, username: username });
      } catch (error) {
        console.log(error);
      }
    },() => {//callback
      console.log("finish loop");
      defer.resolve(test); // when finished loop return result
    }
  );
  return defer.promise;
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...