PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label mongodb. Show all posts
Showing posts with label mongodb. Show all posts

Saturday, December 17, 2022

[FIXED] How to query nested objects?

 December 17, 2022     bson, mongodb, mongodb-query, nested, syntax     No comments   

Issue

I have a problem when querying mongoDB with nested objects notation:

db.messages.find( { headers : { From: "reservations@marriott.com" } } ).count()
0
db.messages.find( { 'headers.From': "reservations@marriott.com" }  ).count()
5

I can't see what I am doing wrong. I am expecting nested object notation to return the same result as the dot notation query. Where am I wrong?


Solution

db.messages.find( { headers : { From: "reservations@marriott.com" } } )

This queries for documents where headers equals { From: ... }, i.e. contains no other fields.


db.messages.find( { 'headers.From': "reservations@marriott.com" } )

This only looks at the headers.From field, not affected by other fields contained in, or missing from, headers.


Dot-notation docs



Answered By - shx2
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, November 15, 2022

[FIXED] How to query- Where In Array Key Value Laravel with Mongodb

 November 15, 2022     laravel, laravel-6.2, mongodb     No comments   

Issue

This is my database Structure

{ 
    "_id":"5e4d4d6fc01c0000cc0009bd",
    "UID":"5e30376327050000b3006cde",
    "delevery_charge":25,
    "order_item":[ 
        { 
            "id":"5e2f4a636c630000f20053bc",
            "Name":"XXXXX",
            "info":"5e26098d94500000870044ac",
        }
    ],
    "subtotal":110,
    "status":1,
    "updated_at":"2020-02-19T14:59:59.000Z",
    "created_at":"2020-02-19T14:59:59.000Z"
}

I want to Find data where order_item=>info ID .. Im using Mongo db

$db = Table::where(''Dont Know what to do)->first();

How can I do that ???


Solution

Have a look at the $elemMatch documentation in MongoDB

db.orders.find({ "order_item" : { "$elemMatch" : { "info" : "5e26098d94500000870044ac" } } });

Should do the trick.



Answered By - jpaljasma
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, November 14, 2022

[FIXED] How to run Find.().One() in the new go-mongo-driver

 November 14, 2022     error-handling, go, mongo-go, mongodb, mongodb-query     No comments   

Issue

Currently we are in the process of migrating the mgo(globalsign) driver to go mongo-driver

And I want some alternative way to do Find.().One()

I tried something like below but it did not help

    login = model.LoginModel{}
    err = mongo.Collection.Find(bson.M{"name": MAXCOUNT}).Decode(&loginCount) 

Returned me back with the below error ,

 error was: cannot transform type []interface {} to a BSON Document: WriteArray can only write a Array while positioned on a Element or Value but is positioned on a TopLevel

not sure whether the new Decode method allows a struct value ?

my struct looks something like below


type LoginModel struct {
Username    string  `json:"username"`
Password    string  `json:"password"`

}

Do i need to have corresponding bson values too ?

Trying to run Find.().One() in go-mongo-driver


Solution

Collection.Find() is designed to query multiple elements. It returns a mongo.Cursor which you can use to iterate over the results or get all using Cursor.All().

If you need a single result, use Collection.FindOne() instead.

For example:

ctx := context.Background() // Use / setup your context
c := ... // acquire mongo.Collection

var login model.LoginModel
err = c.FindOne(ctx, bson.M{"name": MAXCOUNT}).Decode(&login)
// check error


Answered By - icza
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, November 12, 2022

[FIXED] How to create geocoding service (find polygons that intersect a given point)

 November 12, 2022     geocode, memcached, mongodb, node.js, redis     No comments   

Issue

SITUATION

I have a database with 2,000,000 cities. All of them have coordinates of the city center and mostly all - GeoJSON boundaries. I'm trying to implement a geocoding service that would find cities that intersect with a given point using node.js, mongodb, redis, memcached (and golang, if that is necessary, cause I'm just totally new to it )

PROBLEM

I know how to work with points (lat and lng) since both MongoDB and Redis support geoindexes but I've never seen anything about polygons.

I guess MongoDB won't really help cause of its speed (since it work on disks), but any memory database should deal with this problem. The thing is I can't even think of any way to implement it.

I'll be happy if someone point me how to make it. Thanks.


Solution

You may implement a point-in-polygon algorithm yourself. I've done something similar on https://api.3geonames.org

First do a bounding box to identify candidate polygons, then run a PIP. https://en.wikipedia.org/wiki/Point_in_polygon



Answered By - Ervin Ruci
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, November 11, 2022

[FIXED] How do I prevent multiple paypal payments in nodeJs?

 November 11, 2022     mongodb, mongoose, node.js, payment-gateway, paypal     No comments   

Issue

I am really new to node js and trying to integrate Paypal's Payment Gateway into my application.

Upon the success of the payment, the user is redirected to http://localhost:3000/success?paymentId=PAYID-M8MU148234F&token=EC-2111Y&PayerID=YX82JX6Q where our code executes the order and return a payment object (contains order details).

On this page, I want to display the order details to the user.

  1. I want to store the payment object as a JSON.stringify into my Mongoose database for future reference. The issue is that if the user keeps on reloading this page, the code inside app.get('/success'..) will keep on adding the same columns to the mongoose database repeatedly. I am not sure how to prevent that.

  2. Since the payment is actually executed only when this URL is visited by the user, multiple reloads by the user blocks me from Paypal API and gives me the following error:

response: {
    name: 'MAX_NUMBER_OF_PAYMENT_ATTEMPTS_EXCEEDED',
    message: 'You have exceeded the maximum number of 20 payment attempts.',
    information_link: 'https://developer.paypal.com/docs/api/payments/#errors',..........

The only solution I can think of right now is that somehow my /success route executes the payment and stores the data onto the database and then redirects the user to maybe /someOtherPage/ page with the order details as headers. I am not sure how to make this redirect happen and also pass some context (the payment object) at the same time.


Solution

You are using a deprecated v1/payments API and/or PayPal-Node-SDK. You should change your integration to the current v2/checkout/orders and Checkout-NodeJS-SDK.

Make two routes on your server, one for 'Create Order' and one for 'Capture Order', documented here. These routes should return only JSON data (no HTML or text). The latter one should (on success) store the payment details in your database before it does the return (particularly purchase_units[0].payments.captures[0].id, the PayPal transaction ID)

Pair those two routes with the following approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server


The above mostly takes care of this issue and is the recommended solution, as it does not rely on redirects and gives an improved user experience that increases buyer confidence by keeping your site loaded in the background. But to more directly address the issue posed here: when doing an execute or capture API call, set the PayPal-Request-Id HTTP header to something that will persist across retries that are not expected to result in new actions/transactions -- for example simply set this header to the PAYID or OrderId being acted on. This will give idempotent behavior (see API idempotency)



Answered By - Preston PHX
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, November 7, 2022

[FIXED] How do I use $addToSet with objects in mongodb?

 November 07, 2022     arrays, javascript, mongodb, object, set     No comments   

Issue

I want to push only unique objects into an array with $addToSet.

My userSchema has a field bankDetails which should take an array of objects:

const userSchema = new mongoose.Schema(
  {
    bankDetails: [
      {
        cardHolder: String,
        cardNumber: String,
        expiry: String,
        cvc: String,
        cardBrand: String,
      },
    ]
  }
)

I am updating the schema using the following controller function:

exports.createPayment = async (req, res) => {
  const { user, cardHolder, cardNumber, expiry, cvc, cardBrand } = req.body
  const saveDetails = await User.findByIdAndUpdate(
    { _id: user._id },
    $addToSet: {
      bankDetails: {
        cardHolder,
        cardNumber,
        expiry,
        cvc,
        cardBrand,
      },
    },
    { new: true }
  ).exec();
  res.json(saveDetails);
}

The data is saving correctly but Mongo auto generates an _id field every time so technically none of the objects are unique and the objects are repeatedly added.

Is anyone aware of a workaround for this?


Solution

You could check if a bank already exists, and add it only if not present:

exports.createPayment = async (req, res) => {
  const { user, cardHolder, cardNumber, expiry, cvc, cardBrand } = req.body;
  const existingBank = await User.findOne({
    'bankDetails.cardHolder': cardHolder,
    'bankDetails.cardNumber': cardNumber,
    'bankDetails.expiry': expiry,
    'bankDetails.cvc': cvc,
    'bankDetails.cardBrand': cardBrand,
  });
  if (existingBank) return res.json(existingBank);
  const saveDetails = await User.findByIdAndUpdate(
    user._id,
    {
      $addToSet: {
        bankDetails: {
          cardHolder,
          cardNumber,
          expiry,
          cvc,
          cardBrand,
        },
      },
    },
    { new: true }
  ).exec();
  res.json(saveDetails);
};


Answered By - lpizzinidev
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, November 2, 2022

[FIXED] How to Create a nested index in MongoDB?

 November 02, 2022     indexing, mongodb     No comments   

Issue

A. How do I index nested and all of it's values?

B. How do I index valuetwo?

{
    id: 00000,
    attrs: {
        nested:{
            value: value1,
            valuetwo: value2,
        }
    }
}

I've looked here: http://www.mongodb.org/display/DOCS/Indexes, and the docs to my knowledge, aren't clear about indexing things that aren't nested.


Solution

You'd create them just as if you were creating an index on a top level field:

db.collection.createIndex({"attrs.nested.value": 1})

You do need to explicitly create indexes on each field.



Answered By - Bryan Migliorisi
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, October 24, 2022

[FIXED] What can I do to output in MongoDB with $inc from always being decimal with 2 point accuracy? (rounding output)

 October 24, 2022     bson, decimal, mongodb, pymongo, python     No comments   

Issue

So I'm using MongoDB 6.0 (and motor driver in python) and for example I have a code like that:

money = 4.92
from_snowflake = "19251"

await db["bank"].update_one({"snowflake": str(from_snowflake)}, {"$inc": {"balance": -float(money)}})

and assuming the current value of "balance" field in db is 5.91 the final value will be 0.9900000000000002, when I want it to be 0.99

What can I do, so mongodb will be automatically "rounding" this output to 2 point accuracy?


Solution

To preserve numeric fidelity for a financial application, you need to use the Decimal128 BSON type. This is supported in pymongo as follows:

from pymongo import MongoClient
from bson.decimal128 import Decimal128

db = MongoClient()['mydatabase']
money = Decimal128('-4.92')
from_snowflake = "19251"
db["bank"].insert_one({"snowflake": from_snowflake, "balance": Decimal128('5.91')})
db["bank"].update_one({"snowflake": str(from_snowflake)}, {"$inc": {"balance": money}})
print(db["bank"].find_one({}, {'_id': 0}))

prints:

{'snowflake': '19251', 'balance': Decimal128('0.99')}


Answered By - Belly Buster
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, October 20, 2022

[FIXED] How would you pass a property from a nest service to a Schema's virtual property declaration?

 October 20, 2022     mongodb, mongoose, mongoose-schema, nestjs, node.js     No comments   

Issue

I'm migrating an existing nodejs + mongoose API to NestJS. New to this framework, I simply followed the docs on the official website to set up my configuration services & modules, and re-define my schemas to make use of the decorators provided by @nestjs\mongoose.

On my first API, I simply had a ConfigClass that was exported, with Nest, I have a service that is called in my controllers.

What I'm trying to do is to create a mongoose virtual field depending on the value of the configuration. Since my configuration is now stored in a service, I doubt, that I could just import it and use it as-is.

Code-wise, my current configuration module and service look like :

    //app-config.config.ts

    import { registerAs } from '@nestjs/config';

    export const AppConfiguration = registerAs('app', () => ({
      name: process.env.APP_NAME.trim(),
      host: process.env.APP_HOST.trim(),
    }));

    //app-config.service.ts
    
    import { Injectable } from '@nestjs/common';
    import { ConfigService } from '@nestjs/config';
    
    @Injectable()
    export class AppConfigService {
      constructor(private _config: ConfigService) {}
    
      get name(): string {
        return this._config.get<string>('app.name');
      }
    
      get host(): number {
        return this._config.get<number>('app.host');
      }
    }

    //app-config.module.ts
    
    import { Module } from '@nestjs/common';
    import { ConfigModule, ConfigService } from '@nestjs/config';
    import * as Joi from 'joi';
    
    import { AppConfiguration } from './app-config.config';
    import { AppConfigService } from './app-config.service';
    
    @Module({
      imports: [
        ConfigModule.forRoot({
          load: [AppConfiguration],
          validationSchema: Joi.object({
            APP_NAME: Joi.string().default('nest api'),
            APP_HOST: Joi.string().default('localhost.lan'),
          }),
        }),
      ],
      providers: [ConfigService, AppConfigService],
      exports: [AppConfigService],
    })
    export class AppConfigModule {}

My schema would look like :

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';

    @Schema({
      toObject: {
        virtuals: true,
      },
      toJSON: {
        virtuals: true,
      },
    })
    export class Category extends Document {
      @Prop({
        required: true,
      })
      name: string;
    }
    


    export const CategorySchema = SchemaFactory.createForClass(Category);

    //Before my virtual would simply look like this: 
    CategorySchema.virtual('access').get(function (this: Category) {
      // Config would be my configuration class directly imported, 
      //and now accessing my config property as wished.
      const url: URL = new URL('/download', Config.Host);
      // What I'd like to know, now is how I should proceed to get the same result
      // except with AppConfigService.host ? 
      url.searchParams.set('name', this.name);
      return url.toString();
    });

So far, I thought about setting up nodejs globals in the AppConfigModule constructor, I even thought about sending the needed config property to the client, and letting the client do the concatenation.

I'm looking for what would be the cleanest way to do this, I may be unaware of a built-in method.

Thanks in advance. I'll keep this updated if I find an acceptable solution to my problem.


Solution

I finally passed my properties as nodejs globals in my config service.

@Injectable()
export class AppConfigService {

  get port(): number {
    return this._config.get<number>('app.port');
  }

  get host(): string {
    return this._config.get<string>('app.host');
  }

  get url(): string {
    const _url = new URL(`${this.host}:${this.port}`);
    return _url.href;
  }

  constructor(private _config: ConfigService) {
    global.api = this.url;
  }
}

I'll probably move their declarations out of the constructor into a method or even to my app main file (since the service is called at start-up). But for now it's doing the job.



Answered By - CrazyYoshi
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to use populate in mongoose?

 October 20, 2022     mongodb, mongoose, node.js     No comments   

Issue

I have two collections where one holds list of systems and the other holds list of battery attached to the system. I want to use populate method so that when I run the query using system id it shows me the details of battery is also shown. My schema for system and battery are as follows.

const mongoose = require('mongoose');

const { Schema } = mongoose;

const SystemSchema = new Schema(
  {
    serialNumber: String,
    location: String,
    BPIDs: [
      {
        type: Schema.Types.ObjectId,
        ref: 'batteryPack'
      }
    ]
  },
  {
    timestamps: true
  }
);

const Systems = mongoose.model('system', SystemSchema);

module.exports = Systems;

My battery model is as follows:

const mongoose = require('mongoose');

const { Schema } = mongoose;

const batteryPackSchema = new Schema(
  {
    systemSerialNumber: String,
    batteryID: Number,
    batteryVoltage: Number,
    totalCurrent: Number,
    stateOfCharge: Number
  {
    timestamps: true
  }
);

const BatteryPacks = mongoose.model('batteryPack', batteryPackSchema);

module.exports = BatteryPacks;

My query route is as follows:

router.get('/details/:id', async (req, res) => {
  try {
    const deviceDetails = await Systems.findOne({ _id: req.params.id }).populate('batteryPack').lean();
    return res.status(200).send({
      deviceDetails
    });
  } catch (error) {
    return res.status(500).send(error.stack);
  }
});

On running query through postman it shows the following error:

MongooseError: Cannot populate path batteryPack because it is not in your schema. Set the strictPopulate option to false to override. at getModelsMapForPopulate


Solution

I was passing wrong argument inside populate method. The code is working flawlessly now.

const deviceDetails = await Systems.findOne({ _id: req.params.id }).populate('BPIDs').lean();


Answered By - naved17
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the "__v" field in Mongoose

 October 20, 2022     mongodb, mongoose, node.js     No comments   

Issue

I'm using Mongoose version 3 with MongoDB version 2.2. I've noticed a __v field has started appearing in my MongoDB documents. Is it something to do with versioning? How is it used?


Solution

From here:

The versionKey is a property set on each document when first created by Mongoose. This keys value contains the internal revision of the document. The name of this document property is configurable. The default is __v.

If this conflicts with your application you can configure as such:

new Schema({..}, { versionKey: '_somethingElse' })


Answered By - Tony The Lion
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I get full name from first, middle, last name and search among the result for a match?

 October 20, 2022     mongodb, mongoose, node.js     No comments   

Issue

I have a collection as

[
  {
    firstName: "John",
    middleName: "F",
    lastName: "Kennedy"
  }, 
  {
    firstName: "Barack",
    lastName: "Obama"
  }
]

I am trying to create a function that searches the collection by name. I need to concat the names before trying to find a match. I tried the following

User.aggregate([
  {
    "$project": {
      fullName: {
        "$concat": [
          "$firstName",
          " ",
          "$lastName"
        ]
      }
    }
  },
  {
    $match: {
      "fullName": {
        $regex: /[a-z\\s]*oba[a-z\\s]*/i
      }
    }
  }
])

It works for names without middle names. But I need this to work for names with middle names too. When I try to concat middleName, I get an error because the path middleName does not exist on all documents. I could not implement $cond and $exists operators properly make this work. Any kind of help is highly appreciated. Thanks!


Solution

One option is using $ifNull:

db.collection.aggregate([
  {$project: {
      fullName: {$concat: [
          "$firstName",
          " ",
          {$ifNull: [
              {$concat: ["$middleName", " "]},
              ""
          ]},
          "$lastName"
      ]}
  }}
])

See how it works on the playground example



Answered By - nimrod serok
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I populate Ref Id to the orders?

 October 20, 2022     express, javascript, mongodb, mongoose, node.js     No comments   

Issue

How can I get and populate the id ref to the order? I grab the id of the product and user. Then when I use my get method, I will get all the details of the products and users.

For example, my data will show all information

Product a. title b. price c. productImage

User a. username b. studentId

I tried to use populate, but I think I'm doing it wrong.

    export const getOrders = async (req,res) =>{
      try {
      const order = await Order.findOne({productId: '634e91d256326381d5716993'})
                                .populate()
                                .exec()
      res.status(400).json(order)
    } catch (error) {
            res.status(404).json({message: error.message})  
    }
       }

OrderSchema

    const OrderSchema = mongoose.Schema({
        productId: {type:  mongoose.Schema.Types.ObjectId, ref: 'Product', required: true},
        buyerId: {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User'},
        sellerId: {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User'}
    
    })
    
    export default mongoose.model('Order', OrderSchema) 

ProductSchema

    const ProductSchema = mongoose.Schema({
     
        user_id: {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User'},
        title: {type: String},
        description: {type: String},
        categories: {type: Array},
        price: {type: Number},
        productImage: {type: String}
    },
    { timestamps: { createdAt: true } }
     )
    
    export default mongoose.model('Product', ProductSchema)

UserSchema

    const UserSchema = mongoose.Schema({
        username: {type: String, unique: true, required: true},
        password: {type: String,  required: true},
        email: {type: String,  unique: true, required: true},
        studentid: {type: String, unique: true, required: true},
        isAdmin:{type: Boolean, default: false},
        },
       { timestamps: { createdAt: true } }
        )
    
    export default mongoose.model('User', UserSchema)

Solution

You have to specify what you want to populate inside the .populate() method:

await Order.findOne({productId: '634e91d256326381d5716993'})
  .populate([
    { path: 'productId', select: 'title price productImage' },
    { path: 'buyerId', select: 'username studentid' }
  ])
  .exec()



Answered By - NeNaD
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to create nested object schema with mongoose in nodejs?

 October 20, 2022     express, mongodb, mongoose, node.js, reactjs     No comments   

Issue

I am creating collections schema in which i should also include customFields array of object which is defined below. But the schema i tried with , creating new Object Id for each property of customFields object. I need help to include customField object inside my collection schema

Object from FRONT_END

{
    "name": "Ali",
    "topic": "Books",
    "description": "Gonnabe nice collection",
    "owner": "63397103eb71457cdff0c244",
    "customFields": [
        {
            "title": "Title",
            "type": ""
        },
        {
            "title": "Description",
            "type": "textarea"
        }
        {
            "title": "Number",
            "type": "number"
        }
    ]
}

COLLECTION POST ROUTE

collectionRoute.post(
  "/",
  JWTAuthMiddleware,
  adminAndUserOnly,
  async (req, res, next) => {
    try {
      const collection = new CollectionModal(req.body);
      console.log(collection);
      await collection.save();
      const newCollection = await UsersModal.findByIdAndUpdate(
        req.body.owner,
        {
          $push: { collections: { ...collection, owner: req.user._id } },
        },
        { new: true }
      );
      res.status(201).send(newCollection);
    } catch (error) {
      next(error);
    }
  }
);

Schema

import mongoose from "mongoose";
const { Schema, model } = mongoose;

const collectionSchema = new Schema(
  {
    name: { type: String },
    description: { type: String },
    topic: { type: String },
    image: { type: String },
    customFields: [
      {
        fieldNumber: { type: Number },
        fieldMultilineText: { type: String },
        fieldType: { type: String },
        fieldChecked: { type: Boolean },
        fieldDate: { type: Date },
      },
    ],
    owner: { type: Schema.Types.ObjectId, ref: "User" },
    items: [{ type: Schema.Types.ObjectId, require: true, ref: "Item" }],
  },
  { timestamps: true }
);

collectionSchema.index({ "$**": "text" });
export default model("Collection", collectionSchema);

USER SCHEMA

const userSchema = new Schema(
  {
    username: { type: String },
    email: { type: String, unique: true },
    password: { type: String },
    role: { type: String, enum: ["user", "admin"], default: "user" },
    status: { type: String, enum: ["active", "blocked"], default: "active" },
    collections: [{ type: Schema.Types.ObjectId, ref: "Collection" }],
  },
  { timestamps: true }
);

Result

Here is req.body in my server


Solution

You can specify customFields property to be of type Object, so it will accept whatever object you send.

customFields: [{ type: Object }]


Answered By - NeNaD
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How To Query nested mongoDB with $or query in nested field of arrays in NodeJs

 October 20, 2022     javascript, mongodb, node.js     No comments   

Issue

I am trying to query mongoDB collection to fetch and match a specific date range and a specific array of ids, such as brachIds, or servicesIds.

I want the query if it finds this result to return it, so that i can validate if a request already exists in that collection by a specific user.

But whenever I pass array values to the $or [{}] segment of the query, no result comes back when i use $all

what am I doing wrong?

Below code that is working and retrieving the document:

 db.collection("requests")
                    .find({'filter.dateRange.from': {$eq: moment(from, "YYYY-MM-DD").startOf('day').format("YYYY-MM-DD[T]HH:mm:ss.SSS[Z]")},
                        'filter.dateRange.to': {$eq: moment(to, "YYYY-MM-DD").startOf('day').format("YYYY-MM-DD[T]HH:mm:ss.SSS[Z]")},
                     
                        $or: [{'filter.branchesIds': {$eq: branchesIds }},{'filter.groupOfBranchesIds': { $eq: servicesIds }},{'filter.servicesIds': {$eq: groupOfBranchesIds }}]})
                    .toArray()
                    .then(result => {

                           
                            if (result.length) {

                                resolve(result)

                            } else {
                         
                                resolve(result)

                            }
                        }).catch(error => {
                            console.log(error);
                        })

Below code using $all that makes the query not return any document:

            let _branchIds = branchesIds || [];
            let _servicesIds = servicesIds || [];
            let _groupOfBranchesIds = groupOfBranchesIds || [];

 db.collection("requests")
                    .find({'filter.dateRange.from': {$eq: moment(from, "YYYY-MM-DD").startOf('day').format("YYYY-MM-DD[T]HH:mm:ss.SSS[Z]")},
                        'filter.dateRange.to': {$eq: moment(to, "YYYY-MM-DD").startOf('day').format("YYYY-MM-DD[T]HH:mm:ss.SSS[Z]")},
                    
                        $or: [{'filter.branchesIds': {$all: _branchIds }},{'filter.groupOfBranchesIds': { $all: _servicesIds }},{'filter.servicesIds': {$all: _groupOfBranchesIds }}]})
                    .toArray()
                    .then(result => {

                          
                            if (result.length) {

         
                                resolve(result)

                            } else {
                                
                    
                                resolve(result)

                            }
                        }).catch(error => {
                            console.log(error);
                        })

Solution

First you must make sure that your parameters are arrays, so you must convert them as follows:

    if (!branchesIds ) {
    branchesIds = [branchesIds];
}

if (!servicesIds ) {
    servicesIds = [servicesIds];
}

if (!groupOfBranchesIds ) {
    groupOfBranchesIds = [groupOfBranchesIds];
}

Then your query should use the $in:

find({'filter.dateRange.from': {$eq: moment(from, "YYYY-MM-DD").startOf('day').format("YYYY-MM-DD[T]HH:mm:ss.SSS[Z]")},
    'filter.dateRange.to': {$eq: moment(to, "YYYY-MM-DD").startOf('day').format("YYYY-MM-DD[T]HH:mm:ss.SSS[Z]")},
    $or: [{'filter.branchesIds': { $in: branchesIds }},{'filter.groupOfBranchesIds': { $in: groupOfBranchesIds }},{'filter.servicesIds': { $in: servicesIds }}]})
.sort({_created_at: -1})
.toArray()

This should now work. Hope this helps!



Answered By - motionless570
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, October 19, 2022

[FIXED] How companies assign the admin role to a user?

 October 19, 2022     admin, express, mongodb, node.js, rest     No comments   

Issue

I am coding a Rest API with express and I have a middleware to check if a user is admin or not. However, I wonder how companies assign a new user as an admin? Do they edit the database record and change the role there?. I guess that one admin could make another user admin but how is the first admin created? Is there a way to do it in the frontend?


Solution

If it's a software platform (meaning one web address and database for all users of your app) then the first admin user is typically created by running commands on the server command line console to create the right record. Or perhaps by a setup script that is run once. This creates the first admin user, and then that user logs in and creates more admin users via the UI. This typically only ever needs to be done once in the entire lifetime of the project, so no need to have this be a user friendly process.

However, if it's a server you install your own instance of it's common to have a setup wizard, since each new install will need to go through this process, it's worth the effort to make something user friendly. You go to something like myapp.com/setup and then complete a few forms that sets up the first admin user and provides initial configuration and preferences. After this first admin user is setup this setup page would no longer be accessible, so that no other new admin users can be created that way.

Wordpress is a great example of the interactive setup. The end of this video has an example of what that looks like.



Answered By - Alex Wayne
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I verify admin in frontend from backend? (Node.js, Angular, Mongodb)

 October 19, 2022     admin, angular, mean-stack, mongodb, node.js     No comments   

Issue

In the user model, I have a property called isAdmin which default value is false. In MongoDB, I manually created an admin account who has property isAdmin set to true. When I log in as an admin, the program verifies it and terminal shows "admin". But how move this true value to frontend to check if it's admin? What can I write then in frontend?

    isAdmin: {
        type: Boolean,
        default: false
    },
router.post('/login', (req, res) => { 
  let userData = req.body;

  User.findOne({ email: userData.email }, (error, user) => {
    if (error) {
      console.log(error);
    } else {
      if (!user) {
        res.status(401).send('Invalid email');
      } else
        if (user.password !== userData.password) {
          res.status(401).send('Invalid password')
        } else {
          if (user.isAdmin) { // admin <--------------------
            console.log('admin');          
          }
          let payload = { subject: user._id };
          let token = jwt.sign(payload, 'secretKey');
          res.status(200).send({ token });
        }
    }

  })
})

Solution

I return the isAdmin flag alongside the token and it works.



Answered By - Weronika
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to logged in to mongodb as admin?

 October 19, 2022     admin, authentication, console, database, mongodb     No comments   

Issue

I created admin:

> use admin
switched to db admin
> db.createUser(
...   {
...     user: 'admin',
...     pwd: 'password',
...     roles: [ { role: 'root', db: 'admin' } ]
...   }
... );
Successfully added user: {
        "user" : "admin",
        "roles" : [
                {
                        "role" : "root",
                        "db" : "admin"
                }
        ]
}
> exit;

But when I wanted to logged in I get an error:

> use admin
switched to db admin
> db.auth('admin','password');
Error: Authentication failed.
0

I tried also with:

mongo --port 27017  --authenticationDatabase "admin" -u "admin" -p "password"

and:

mongo localhost:27017/admin -u admin -p password

But it also doesn't work.


Solution

After restarting my PC, I was able to log in to mongodb as admin.



Answered By - Weronika
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to assign ‘author’ role to User in strapi.io?

 October 19, 2022     admin, frontend, mongodb, node.js, strapi     No comments   

Issue

In the user table when I am trying to assign a role to a user, it is showing public and authenticated options only. How to select ‘author’/‘editor’ or any other to the user through the admin panel and also through API?


Solution

First of all, you need to understand that the Editor, Author & Super Admin are roles for admin panel users only. So basically, it will only control/limit what the user can do after logging in into the admin panel (http://localhost:1337/admin). Additionally, these roles can only be assigned to the admin panel users which can be created by visiting the following module:

http://localhost:1337/admin/settings/users.

Now coming to your question, as to why we can't assign Editor/Author to users in the users collection, it's because the roles assigned to these users are in a separate module:

http://localhost:1337/admin/settings/users-permissions/roles

The roles created in this module are basically assigned to API consumers. So you could create roles of your own choice in this module and then:

  1. Limit the set of APIs this role can access
  2. Define whether the route will be public or private to this role
  3. Set rate limiting

Once you create the roles of your choice in this module, then you can go to users collection module.

http://localhost:1337/admin/plugins/content-manager/collectionType/plugins::users-permissions.user?page=1&pageSize=10&_sort=username:ASC

You could then create users (API consumers/users) who will have their own set of credentials (email & password) which can then be used for acquiring the bearer token.

So, to sum up, just create the roles you want to assign to users in this module and then use the user with that role for acquiring bearer token, following which you can call the APIs with that token. Simple!

P.S: Bearer Token is used on the headers for accessing private routes enabled for that particular user role.



Answered By - Salvino D'sa
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the "admin" database in mongodb?

 October 19, 2022     admin, mongodb     No comments   

Issue

I was practicing ont mongodb documentation : https://docs.mongodb.com/manual/tutorial/enable-authentication/

and I can't figure out if the "admin" database in the example is just a database created for the tutorial or if it is a built-in database made specifically for managing admin users.

Thanks in advance.


Solution

When you create a database in MongoDB you don’t have authentication enabled, the user has all the privileges and roles over that database, you even have access to the database remotely if the firewall doesn’t have port 27017 blocked.

There are two special databases admin and local, users of these databases can perform operations such as those mentioned in the document on other databases to which they have access. In a development environment it is convenient not to worry about users and passwords, however, when users interact with the database remotely on an application, it is essential to activate user authentication.



Answered By - D Mares
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing