2

How can i execute this mongodb query through node js (mongoose). i have two tables with the follwoing schemas, i want to fetch username and password from users table and fetch full name from the info table.

var infoSchema = mongoose.Schema({ khatam_id: String, user_id: String, fullname: String, });

var usersSchema = mongoose.Schema({ user_id: String, username: String, password: String, });

5
  • 1
    can you please specify what error or problem you are facing, the question is not very clear about what the problem is really. Commented Jul 9, 2018 at 5:37
  • suppose i have table users and another table info, info table have user_id i want to fetch all data from info table with an extra item full name which can be fetch from users table Commented Jul 9, 2018 at 5:38
  • still can you add the stack trace or the exact problem you just wrote the query here but the problem is not described it needs more information to solve the question. Commented Jul 9, 2018 at 5:39
  • add your mongoose model Commented Jul 9, 2018 at 5:46
  • So can you please edit the question with the information you have provided in the comment. Commented Jul 9, 2018 at 5:47

6 Answers 6

1

i don't know if you're a hot shot but if you are you can use this.

userSchema.virtual('infos', 
 {
   ref: 'Info',
   localField: 'user_id',
   foreignField: 'user_id',
 })

Assuming u name you're infoSchema as Info model ,mongodb converts it to infos in case you didn't know thats why the virtual field will be called as infos ref obviously a reference to Info model localField is the field referring the userSchema unique id and foreignField is the field u are referring in the infoSchema which matches the unique value that localfield u mentioned . Finally, along with all the fields in your userSchema add this

{
toJSON: { virtuals: true },
toObject: { virtuals: true },
}

so when u query for user Give it a shot it really comes in handy. Note: it doesn't actually create a field in the database (virtual duh.) it just populates your response object for front end rendering which is actually better.

Sign up to request clarification or add additional context in comments.

Comments

1

Connect to MongoDB: Make sure MongoDB service is running before the program execution.

 var mongoose = require("mongoose");
    mongoose.connect("mongodb://localhost:27017/your-database");
    mongoose.Promise = global.Promise;
    var connection = mongoose.connection;
    connection.once('open', function() {
       console.log('connected to database);

    });

    connection.on('error', function() {
      console.error('Mongoose connection error");

     });
    process.on('SIGINT', function() {
       mongoose.connection.close(function() {
       console.log('Mongoose connection disconnected due to app SIGINT.');
     });

   });

create user schema :

const Schema = mongoose.Schema;
    const usersSchema = new Schema({
     user_id: String,
     username: String,
     fullname: String
    });

  const Users = mongoose.model('Users', usersSchema );

Run Query like this:

 Users.findOne({query})
    .then(function(user){
      // do something
     })
    .catch(function(err){
      // handle error
     }) 

Comments

1

Assuming you know how to set setup mongoose and connect your database and only need the correct query let me share something i noticed with the models you provided. I don't think there is a need for 2 collections as you can store the same thing under one collection because it saves the time for lookup for the user data from info schema. So user schema can be

var usersSchema = mongoose.Schema({ 
  user_id: String, 
  username: String, 
  password: String,
  khatam_id: String,
  fullname: String
});

And using the following query you can get the user details

Users.findOne({})
.then(function(user){
  // do something
 })
.catch(function(err){
  // handle error
 }) 

This is much more efficient and faster compared to using aggregate queries or mongoose populate functions.

If the above method is not suitable for you you can try the mongoose populate function.

UserSchema = new mongoose.Schema({
    user_id: String,
    password: String,
},
// schema options: Don't forget this option
// if you declare foreign keys for this schema afterwards.
{
    toObject: {virtuals:true},
    // use if your results might be retrieved as JSON
    // see http://stackoverflow.com/q/13133911/488666
    //toJSON: {virtuals:true} 
});

UserInfoSchema = new mongoose.Schema({
  user_id: String,
  khatam_id: String,
  username: String,
  fullname: String,
});


// Foreign keys definitions

UserSchema.virtual('userDetails', {
  ref: 'UserInfoSchema',
  localField: 'user_id',
  foreignField: 'user_id',
  justOne: true // for many-to-1 relationships
});


// Models creation

var UserSchema = mongoose.model('UserSchema', UserSchema);
var UserInfoSchema = mongoose.model('UserInfoSchema', UserInfoSchema);


// Querying

UserSchema.find({...})
    // if you use select() be sure to include the foreign key field !
   .select({.... user_id ....}) 
   // use the 'virtual population' name
   .populate('userDetails')
   .exec(function(err, books) {...})

Comments

0

install mongoose in your machine

npm install mongoose

import mongoose lib

const mongoose = require('mongoose');
const Schema = mongoose.Schema, ObjectId = Schema.ObjectId;

connect to mongodb and create schema for your table

mongoose.connect('mongodb://localhost/myappdatabase');

const usersSchema = new Schema({
 _id: ObjectId,
 user_id: String,
 username: String,
 fullname: String
});

const Users = mongoose.model('Users', usersSchema );

Find user from "Users" table using mongo query

Users.find({<here you can write your mongo query>}, function (err, docs) {
  // docs.forEach
});

Comments

0

you have to use aggregate

db.users.aggregate([
{
   $lookup:
     {
       from: "info",
       localField: "user_id",
       foreignField: "_id",
       as: "userInfo"
     }
},
{ "$unwind": "$userInfo" },
])

Comments

0

You can use this query to get those types of records what you want:

db.users.aggregate([
{  $lookup: {
       from: "info",
       localField: "user_id",
       foreignField: "user_id",
       as: "userInfo"}},
{ "$unwind": "$userInfo" }])

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.