Showing posts with label MongoDB. Show all posts
Showing posts with label MongoDB. Show all posts

Sunday 9 July 2023

Solution : Error occured promise pending in nodejs mongodb

 Today I will try to share about information how to solved  "Solution: Error occurred promise pending in nodejs mongodb" .

Let's see example scripts error resutls : 

const va = User.findOne({email:  profile?.email})
      .then((docs)=>{
         
          //console.log(docs);
        return docs;
      })
      .catch((err)=>{
          console.log(err);
         
      });


The above script, results message is something like an error promise pending.

To solve these problems try use async scripts of the first function and don't forget to put await scripts keyword. like the scripts below.

exports.signInGoogle = async function(req, res, next){
  try {

      const va = await User.findOne({email:  profile?.email})
      .then((docs)=>{
         
          //console.log(docs);
        return docs;
      })
      .catch((err)=>{
          console.log(err);
          //res.json({ token: jwt.sign({ email: user.email, fullName: user.fullName, _id: user._id }, 'RESTFULAPIs') });
      });

      console.log(va);

};


These scripts work for me, and hope work with you too. Thanks for visiting my blog. Hope this blog can helping you.


Thursday 22 June 2023

How to Create a MongoDB ObjectId from a String in nodeJS with MongoDB

 You can translate a MongoDB ObjectId from a string to an ObjectId instance using the ObjectId class exported from the MongoDB Node.js driver. Pass your string value as an argument to the constructor and the package creates the 12-byte ObjectId instance:

import { ObjectId } from 'mongodb'

const objectId = new ObjectId('your-object-id-as-string')  

Please notice: the ObjectId constructor validates your input and throws an error if the provided string value is not a valid hex representation of an ObjectId. The hex format is the one you know from MongoDB, like 61dc2d31bbe643fc32022a5f.

Be prepared to catch the related MongoDB error when users try to challenge your backend with non-ObjectId string values.


Source : https://futurestud.io/tutorials/mongodb-how-to-create-an-objectid-from-a-string-in-node-js

How to lookup with localField and foreignField more than one in MongoDB

  Today I will try to share information on "How to lookup with localField and foreignField more than one in MongoDB", This information may be rarely short because just seeing a piece of code only. But this code work for MongoDB current version.

So let's see a piece of code below  :

  db.detailactivities.aggregate([{$lookup:
    {
      from: "activities",
      localField: "user_id",
      localField: "activity_id",
      foreignField: "user_id",
      foreignField: "_id",
     as: "products"
    }
  }]);

Output/result of my project only:

  {
    _id: ObjectId("6493ef3c6ee4fdb45bb6e4db"),
    user_id: ObjectId("648aecc8ea9841c8bec570a7"),
    activity_id: ObjectId("6491a39cbb3be69d2f793ae7"),
    doing_activity: 'doo',
    description: 'd',
    created: 2023-06-22T06:50:36.199Z,
    __v: 0,
    products: [
      {
        _id: ObjectId("6491a39cbb3be69d2f793ae7"),
        user_id: '648aecc8ea9841c8bec570a7',
        activity: 'Blogger',
        description: 'Blogger',
        created: 2023-06-20T13:03:24.682Z,
        __v: 0
      }
    ]
  }


Ok, that is just a little information, hope can help you. Another question please leave comments below. Thanks for your visiting my blog.






How to using aggregate lookup mongoDB in node js API server

 Today i will try share about information "How to using aggregate lookup mongoDB in node js API server", This is information maybe rerely short because just seeing piece of code only. But this code work for mongodb and nodejs currently version.

So lets see piece of code below  :

exports.showAllDetailActivity = async function(req, res){


  dy.aggregate([{$lookup:
    {
     from: "activities",
     localField: "activity_id",
     foreignField: "_id",
     as: "products"
    }
    }]).then((docs)=>{
      res.json(docs)
      })
      .catch((err)=>{
        console.log(err);
        res.status(401).json({ message: 'Something Wrong' });
    });


}

Output / result  of my project only:

[
    {
        "_id": "6493ef3c6ee4fdb45bb6e4db",
        "user_id": "648aecc8ea9841c8bec570a7",
        "activity_id": "6491a39cbb3be69d2f793ae7",
        "doing_activity": "d",
        "description": "d",
        "created": "2023-06-22T06:50:36.199Z",
        "__v": 0,
        "products": [
            {
                "_id": "6491a39cbb3be69d2f793ae7",
                "user_id": "648aecc8ea9841c8bec570a7",
                "activity": "Blogger",
                "description": "Blogger",
                "created": "2023-06-20T13:03:24.682Z",
                "__v": 0
            }
        ]
    }
]


Ok that is just a little information from, hope can helping you. Another question please leave comments below. Thanks for your visiting my blog.


Wednesday 21 June 2023

How to copy paste in MongoSh

 Today i will to try to share information "How to copy paste in MongoSh", as a generally we used to using command ctr + c and ctr +v in keyboard, but the problem in mongosh not working to using that  command. And then the solution of the problem is :

use keyboard command Ctrl + Shift + C to copy data.

use keyboard command Ctrl + Shift + V to paste data.

That is the information of the "How to copy paste in MongoSh". Hope this information can helping you, Thanks

Tuesday 20 June 2023

How to so select certain colum to be shown in MongoDB

 Today i will try to share about "How to so select certain colum to be shown in MongoDB", Ok let see example scripts below :

db.demo415.find({},{_id:0,ClientName:1});

The out example for this script are :

{ "ClientCountryName" : "US" }
{ "ClientCountryName" : "UK" } 

{ "ClientCountryName" : "AUS" } 


Note : Parmeter with _id = 0 or ClientName = 1, value 0 not displaying the data and value 0 is diplaying the data.


Hope this information can helping you, Thanks.




Source : https://www.tutorialspoint.com/how-to-select-specific-columns-in-mongodb-query


Sunday 18 June 2023

How to update data by id in mongodb and nodejs REST Api

 Today i will share again about imformation "How to update data by id in mongodb and nodejs REST Api"

Ok lets check it out following codes :

exports.updateDataActivityById = async function(req, res)
{
    let id = {"_id": req.body.id};
    let editValue = {$set: {activity: req.body.activity, description: req.body.description }};
    dy.updateOne(id, editValue)
    .then((docs)=>{
     
        res.json(docs);
    })
    .catch((err)=>{
        console.log(err);
        res.status(401).json({ message: 'Something Wrong' });
    });
};


dy.updateOne(id, editValue)

= This is main script to update data by value id.

Ok just that is information I want to share . Hope this information can helping you. Thanks


How to delete data by id in nodejs and mongodb API REST

 Today i will try to share information that is "How to delete data by id in nodejs and mongodb API REST".

Now lets see piece of code below :

exports.deleteActivityById =  async function(req, res, next){
 
  dy.findByIdAndDelete(req.body.id)
  .then((docs)=>{
     
    res.json(docs);
  })
  .catch((err)=>{
      console.log(err);
      res.status(401).json({ message: 'Something Wrong' });
  });
};


dy.findByIdAndDelete(req.body.id)

This is main code to delete data by id,

Hope this information can helping you, and any questions please leave a comment below thanks.


Wednesday 14 June 2023

How to connecting multiple database mongodb in nodejs server

Today i will try to share about  "How to connecting multiple database mongodb in nodejs server", so let see and try to anlyzing script below :

db.js

const mongoose = require('mongoose')

const MONGO_URI =
    'mongodb+srv://owlhacking:mypassword@cluster0.ls5sgez.mongodb.net/qrCodeData?retryWrites=true&w=majority'
const MOBILE_URI =
    'mongodb+srv://owlhacking:mypassword@cluster0.lpqs0es.mongodb.net/Cluster0?retryWrites=true&w=majority'

const connectDBs = () => {
    try {
        const qrCodeDb = mongoose.createConnection(MONGO_URI, {
            useUnifiedTopology: true,
            useNewUrlParser: true
        })
        const userDB = mongoose.createConnection(MOBILE_URI, {
            useUnifiedTopology: true,
            useNewUrlParser: true
        })
        return { qrCodeDb, userDB }
    } catch (error) {
        console.error(`Error:${error.message}`)
        process.exit(1)
    }
}

module.exports = { connectDBs }

model.js

const { default: mongoose } = require('mongoose')
const { connectDBs } = require('../config/db')

const qrSchema = mongoose.Schema({
    qrInformation: {
        type: String,
        required: true
    },
    qrImage: {
        type: String,
        required: true
    },
    timeStamp: {
        type: String,
        default: Date()
    }
})

const userSchema = new mongoose.Schema({
    fullname: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    }
})
const { qrCodeDb, userDB } = connectDBs()

module.exports = {
    userSchema: userDB.model('user', userSchema),
    Qrcode: qrCodeDb.model('Qrcode', qrSchema)
}


Hope this information can helping you. Thanks


Source : https://gist.github.com/hackinf0/4f97a6a7e820cb612e0ff5c39139d08f

Wednesday 7 June 2023

Auth access JWT node js and mongodb

 

What is JWT?

JWT(JSON Web Token) is a token format. It is digitally-signed, self-contained, and compact. It provides a convenient mechanism for transferring data. JWT is not inherently secure, but the use of JWT can ensure the authenticity of the message so long as the signature is verified and the integrity of the payload can be guaranteed. JWT is often used for stateless authentication in simple use cases involving non-complex systems.

Here's an example of JWT:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Im9sYXR1bmRlZ2FydWJhQGdtYWlsLmNvbSIsIm

Now, let's authenticate/protect some routes.

Pre-requisites:

  • Basic knowledge of HTML/JavaScript
  • NodeJS should be installed in your system.
  • express module for creating the server.
  • mongoose module for MongoDB connection and queries.
  • bcrypt module for hashing.

you can install all required packages by using following command:

npm install express mongoose bcrypt  --save

Step 1. First, create a directory structure as below :

JWTApp

-api
--models
----userModel.js
--controllers
----userController.js
--route
----userRoute.js
--server.js

Step 2. Install “jsonwebtoken” packageby using following command

 npm install jsonwebtoken -- save

Step 3. Create the user model

In the api/models folder, create a file called user userModel.js by running touch api/models/userModel.js.

In this file, create a mongoose schema with the following properties:

  • fullName
  • email address
  • password
  • the created date

Add the following code

'use strict';

var mongoose = require('mongoose'),
  bcrypt = require('bcrypt'),
  Schema = mongoose.Schema;

/**
 * User Schema
 */
var UserSchema = new Schema({
  fullName: {
    type: String,
    trim: true,
    required: true
  },
  email: {
    type: String,
    unique: true,
    lowercase: true,
    trim: true,
    required: true
  },
  hash_password: {
    type: String
  },
  created: {
    type: Date,
    default: Date.now
  }
});

UserSchema.methods.comparePassword = function(password) {
  return bcrypt.compareSync(password, this.hash_password);
};

mongoose.model('User', UserSchema);

Step 4. Create the user handlers

In the api/controllers folder, create a file called user userController.js by running touch api/controllers/userController.js

In the userController file, create three different handlers to handle by using the following code

'use strict';

var mongoose = require('mongoose'),
  jwt = require('jsonwebtoken'),
  bcrypt = require('bcrypt'),
  User = mongoose.model('User');

exports.register = function(req, res) {
  var newUser = new User(req.body);
  newUser.hash_password = bcrypt.hashSync(req.body.password, 10);
  newUser.save(function(err, user) {
    if (err) {
      return res.status(400).send({
        message: err
      });
    } else {
      user.hash_password = undefined;
      return res.json(user);
    }
  });
};

exports.sign_in = function(req, res) {
  User.findOne({
    email: req.body.email
  }, function(err, user) {
    if (err) throw err;
    if (!user || !user.comparePassword(req.body.password)) {
      return res.status(401).json({ message: 'Authentication failed. Invalid user or password.' });
    }
    return res.json({ token: jwt.sign({ email: user.email, fullName: user.fullName, _id: user._id }, 'RESTFULAPIs') });
  });
};

exports.loginRequired = function(req, res, next) {
  if (req.user) {
    next();
  } else {

    return res.status(401).json({ message: 'Unauthorized user!!' });
  }
};
exports.profile = function(req, res, next) {
  if (req.user) {
    res.send(req.user);
    next();
  } 
  else {
   return res.status(401).json({ message: 'Invalid token' });
  }
};

Note: A hash password was saved in the database using bcrypt.

Step 6. In the api/route folder, create a file called user userRoute.js and add the following code:

'use strict';
module.exports = function(app) {
    var userHandlers = require('../controllers/userController.js');
    // todoList Routes
    app.route('/tasks')
        .post(userHandlers.loginRequired, userHandlers.profile);
    app.route('/auth/register')
        .post(userHandlers.register);
   app.route('/auth/sign_in')
        .post(userHandlers.sign_in);
};

Step 7. Add the following code in server.js

'use strict';

var express = require('express'),
  app = express(),
  port = process.env.PORT || 3000,


  User = require('./api/models/userModel'),
  bodyParser = require('body-parser'),
  jsonwebtoken = require("jsonwebtoken");

const mongoose = require('mongoose');
const option = {
    socketTimeoutMS: 30000,
    keepAlive: true,
    reconnectTries: 30000
};

const mongoURI = process.env.MONGODB_URI;
mongoose.connect('mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb', option).then(function(){
    //connected successfully
}, function(err) {
    //err handle
});

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(function(req, res, next) {
  if (req.headers && req.headers.authorization && req.headers.authorization.split(' ')[0] === 'JWT') {
    jsonwebtoken.verify(req.headers.authorization.split(' ')[1], 'RESTFULAPIs', function(err, decode) {
      if (err) req.user = undefined;
      req.user = decode;
      next();
    });
  } else {
    req.user = undefined;
    next();
  }
});
var routes = require('./api/routes/userRoutes');
routes(app);

app.use(function(req, res) {
  res.status(404).send({ url: req.originalUrl + ' not found' })
});

app.listen(port);

console.log(' RESTful API server started on: ' + port);

module.exports = app;

Step 9. Now you just need to run the project by using the following command and try logging by using the JWT.

npm start

Step 10. Open Postman and create a post request to localhost:3000/auth/register as below:

Postman register

Step 11. After this, let’s sign with this URL localhost:3000/auth/sign_in . Enter the keys and values for email and password

Postman signin

Under the value, add JWT and the token with a space between, like so:

JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Im9sYXR1bmRlZ2FydWJhQGdtYWlsLmNvbSIsImZ1bGxOYW1lIjoiT2xhdHVuZGUgR2FydWJhIiwiX2lkIjoiNThmMjYzNDdiMTY1YzUxODM1NDMxYTNkIiwiaWF0IjoxNDkyMjgwMTk4fQ.VcMpybz08cB5PsrMSr25En4_EwCGWZVFgciO4M-3ENE

Step 11. Then, enter the parameters for the key and value for fetching the profile. You want to create as shown below and send:

Postman signin

As we have seen it is fairly easy to build a JWT authentication system with NodeJS, You can found the complete code used in this tutorial here.











Source : https://www.loginradius.com/blog/engineering/nodejs-and-mongodb-application-authentication-by-jwt/