Home > OS >  How to save data as int using mongodb compass and koa js. Value automatically convert into String
How to save data as int using mongodb compass and koa js. Value automatically convert into String

Time:06-28

I am creating a simple CRUD application using mongodb compass and koa js. This is the dao file I am using

const products = require('./index').db('store').collection('products');

const ObjectId = require('mongodb').ObjectId;

const save = async ({name, description,qty,price}) => {
    const result = await products.insertOne({name, description,qty,price});
    return result;
}

const getAll = async () => {
    const cursor =  await products.find();
    return cursor.toArray();
}

const update = async (id, {name,description,qty,price}) => {
    const result =  await products.replaceOne({_id:ObjectId(id)}, {name,description,qty,price});
    return result;
}

const removeById = async id => {
    await products.deleteOne({_id:ObjectId(id)});
}

module.exports = {save, getAll,update,removeById};

Here is the API File I used.

const {save,getAll,update,removeById} = require ('../dal/products.dao');

const createProduct = async ({name, description,qty,price})=>{
    const product = {
        name,description,qty,price
    }
    return await save(product);
}

const getProducts = async () => {
    return await getAll();
}

const deleteProduct =  async id => {
    return await removeById(id);
}

const updateProduct = async (id, {name, description,qty,price})=>{
    return await update(id, {name, description, qty, price});
}

module.exports = {
    createProduct, getProducts,deleteProduct,updateProduct
}

Finally this is the router I used,

const Router = require('@koa/router');

const {createProduct, getProducts,deleteProduct,updateProduct } = require('../API/products.api');

const router = new Router({
    prefix:'/products'
})

router.get('/',async ctx=>{
    ctx.body = await getProducts();
})

router.post('/',async (ctx)=>{
    let product = ctx.request.body;
    product = await createProduct(product);
    ctx.set('Content-type','application.json');
    ctx.response.status = 201;
    ctx.body = product;
})

router.delete('/:id',async ctx=>{
    const id = ctx.params.id;
    await deleteProduct(id);
    ctx.body = "Item deleted!";
});

router.put('/:id',async ctx=>{
    const id = ctx.params.id;
    let product = ctx.request.body;
    product = await updateProduct(id,product);
    ctx.response.status = 200;
    ctx.body = product;
});

module.exports = router;

I made the connection using this code in index.js

const {MongoClient} = require("mongodb");

const client =  new MongoClient('mongodb://localhost:27017',{
    useNewUrlParser: true,
    useUnifiedTOpology: true
});

client.connect(err => {
    if(err){
        console.error(err);
        process.exit(-1);
    }
    console.log("MongoDB connection success..!");
})

module.exports = client;

App.js is as below,

const bodyParser = require('koa-bodyparser');
const cors = require('@koa/cors');
const koa = require('koa');
const mongodb = require('./dal/index.js');
const productRoutes = require('./routes/products.routes');
const userRoutes = require ('./routes/users.routes');

const app = new koa();
app.use(bodyParser());
app.use(cors());

app.use(productRoutes.routes()).use(productRoutes.allowedMethods());
app.use(userRoutes.routes()).use(userRoutes.allowedMethods());

const PORT = 3000;

app.listen(PORT,()=>{
    console.log("Server is up and running on ", PORT,"...");
});

When I pass value using postman as Integer it saves in db as an Integer. But When I use react frontend to add data it automatically converts into String value. I want to keep it as Integer.

I tried using input type as 'Number'. But No luck.

Can you please help me.

CodePudding user response:

Please refer the below code snippet. You can use parseInt() to force convert value to Integer. Then assign the value and save it in the database.

const saveUser = async ({name, email,address,phone, type ,password}) => {
    let tpno = parseInt(phone);
    const result = await users.insertOne({name, email,address,phone:tpno, type ,password});
    return result;
}
  • Related