egx
egx

Reputation: 399

Fetching data from Mongo based on ObjectID on logged in user

I have two collections in my Mongo DB which looks like this:

Documents

User:

id: ObjectId ("5fb39e3d11eaad3e30cfb1b0")
userName: "Tobias"
password: "yyy"

id: ObjectId ("5fb3c83fb774ff3340482250")
userName: "Thor"
password: "xxx"

Courses:

id: ObjectId ("5fb3cf3da8227e101826e2db")
CourseName: "Design"
userId: "5fb39e3d11eaad3e30cfb1b0" (THIS IS THE SAME AS THE OBJECT ID FOR THE FIRST USER) 

When a user is logging in, the user can add a course and the object ID for the logging in user will be added to the collection in MongoDB along with the coursename (just as in the example above).

My question is, how do I show only the courses which matches the user which are logged in? I'm using mongoose for user-login, express for server conn, ejs for view, and VueJS for control.

I'm comming from relationel databases, so not sure if the approch i'm trying out here with joining the objectID's is good practice.

Upvotes: 1

Views: 961

Answers (2)

Mahesh
Mahesh

Reputation: 371

You can use find() or findOne() function.

courses.findOne(function (err, course) {
  if (err) return handleError(err);
  if (course) {
//do Something
  }
});

Upvotes: 0

Ilijanovic
Ilijanovic

Reputation: 14904

In mysql you join, in mongodb you use $lookup

   CoursesModel.aggregate([
      {
        $lookup: {
          from: UserModel.collection.name,
          localField: "userId",
          foreignField: "_id",
          as: "user"
        }
      },
    ]).then(result => {
       console.log(result);
    })

In your result you will have an additional field called user. This will be an array with all documents that matched the userId

Instead of UserModel.collection.name you could use an string as name. But i prefer using the collection name programatically.

Upvotes: 1

Related Questions