How to select two table (document) value at a time by user id in mongoose?

后端 未结 3 1365
抹茶落季
抹茶落季 2021-01-21 16:05

I am using NodeJs, ExpressJs with Mongodb and Mongoose. I want to select two document\'s value by user id.

I have three model User, Academic and Career. I have made a re

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-21 16:45

    Since Mongoose is used here: This can achieved using Populate. populate is pretty similar/analogues to what you would achieve via $lookup aggregation in pure mongo.

    An alternative option: If you would adjust your schemas like this to really leverage Mongoose.

    //user model
    const userSchema = new mongoose.Schema({
      name: { type: String },
      email: { type: String },
      career: {
        type: Schema.Types.ObjectId,
        ref: "Career"
      },
      academic: {
        type: Schema.Types.ObjectId,
        ref: "Academic"
      }
    });
    
    //academics and career can be array of documents as well -if required
    const user = mongoose.model("User", userSchema);
    
    // academic model
    const academicSchema = new mongoose.Schema({
      academicLevel: { type: String },
      passYear: { type: Number }
    });
    const academic = mongoose.model("Academic", academicSchema);
    
    // career model
    const careerSchema = new mongoose.Schema({
      jobTitle: { type: String },
      company: { type: String }
    });
    const career = mongoose.model("Career", careerSchema);
    

    Populate query: To get user's academics and career docs

    const user = await User.find({ _id: requestedUserId })
      .populate("academic")
      .populate("career")
      .exec();
    

    NOTE: requestedUserId is the user id that to be filtered upon.

提交回复
热议问题