Skip to content Skip to sidebar Skip to footer

How To Select Two Table (document) Value At A Time By User Id In Mongoose?

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 relation with

Solution 1:

For what I've read in the docs, I think what you are looking for is something like so:

const career = await Career.find({ user: user._id});
const academics = await Academics.find({ user: user._id});

Or if you want to execute both queries at the same time:

const careerOperation = Career.find({ user: user._id});
const academicsOperation = Academics.find({ user: user._id});

const [
    career, 
    academics
] = await Promise.all([career.exec(), academics.exec()]);

Hope to have helped!

Solution 2:

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 modelconst 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 requiredconst user = mongoose.model("User", userSchema);

// academic modelconst academicSchema = new mongoose.Schema({
  academicLevel: { type: String },
  passYear: { type: Number }
});
const academic = mongoose.model("Academic", academicSchema);

// career modelconst 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.

Solution 3:

This is the simplest query we can make for find user with given query Id

router.get('/getInfoById/:id', async (req, res) => {
     const user = await User.aggregate([
           { $match: { _id: mongoose.Types.ObjectId(req.query.id) }},
           { $lookup: {
              from: "career",
              localField: "_id",
              foreignField: "user",
              as: "careers"
           }},
           { $lookup: {
              from: "academic",
              localField: "_id",
              foreignField: "user",
              as: "academics"
           }}
        ])
    res.send(user);
});

Post a Comment for "How To Select Two Table (document) Value At A Time By User Id In Mongoose?"