1

I have user model

const mongoose = require("mongoose");
const uniqueValidator = require("mongoose-unique-validator");

const userSchema = mongoose.Schema({
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  isEmailVerified: { type: Boolean },
  registrationStep: { type: Number, enum: [0,1,2,3]},
  regDate: { type: Date },
  companyName: { type: String },
  oib: { type: String },
  telephone: { type: String },
  address: { type: String },
  city: { type: String },
  countryCode: { type: String },
  postalCode: { type: String },
  userType: { type: String, enum:['firms','drivers','both']},
  approved: { type: Boolean },
  isAdmin: { type: Boolean }
});

userSchema.plugin(uniqueValidator);

module.exports = mongoose.model("User", userSchema);

and documents model

const mongoose = require("mongoose");

const docsSchema = mongoose.Schema({
  docsPath: { type: String, required: true },
  creator: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
  docType: { type: String, enum:['isr','lmp','pocmr'], required: true }
});

module.exports = mongoose.model("Docs", docsSchema);

I want to join collections so that for every user exists the user_docs field with docs data as in code below. I'm trying to do that with joining _id with creator as it is defined when creating a document

exports.getUsersAndDocs = (req, res, next) => {
  const query = User.aggregate([
    {
    $lookup: {
      from: "Docs",
      localField: "_id",
      foreignField: "creator",
      as: "user_docs"
    }
  }]);
  query
    .then(fetchedUsers => {
      res.status(200).json({
        message: "Users fetched successfully!",
        users: fetchedUsers,
      });
    })
    .catch(error => {
      res.status(500).json({
        message: "Fetching users failed!"
      });
    });
};

I'm recieveing empty user_docs array. Thank you for your help

1 Answer 1

1

If someone has the same problem. I solved it by changing

from: "Docs"

to

from: Docs.collection.name
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.