skip to Main Content

I want to request a certain userId via NodeJs but I always receive all documents from MongoDb, independent of the userId I provide.

This is my route:

router.get('/wallet/showWallet/', walletController.showWallet)

Controller:

const showWallet = async(req,res)=>{
    try {
        let user = req.query.userId;
        const wallet = await walletService.getWalletById(user);
        res.json(wallet);
     } catch (error) {
        res.status(500).json({error: error})
     }
}

Service:

function walletService() {
    function getWalletById(user) {
        try {
            const walletResponse =  walletModel.find({userId: new ObjectId(user)}, {amount: 1, _id: 0});1, _id: 0});
            return walletResponse;
        } catch (error) {
            console.log(`Wallet not found. ${error}`)
        }       
    }
    return {
        getWalletById: getWalletById,
    }
}

Model:

const mongoose  = require("mongoose")

const walletModel = new mongoose.Schema({
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref : 'User'
    },
    amount: {
        type: Number
    },
    last_recharge_date: {
        type: Date
    },
    expiry_date: {
        type: Date
    },
    isDeleted: {
        type: Boolean
    },
    isActive: {
        isActive: Boolean
    },
})

const wallet = mongoose.model("wallets", walletModel)
module.exports = wallet;

Postman:

https://someUrl/api/wallet/showWallet?userId=626b9f5908b0fef1b09a55e4

MongoDb:

enter image description here

Result from Postman:

enter image description here

I really cannot find a way to solve this problem!

Maybe somebody can help me, please?

Thanks in advance!

2

Answers


  1. try this one :

    function walletService() {
        function getWalletById(user) {
            try {
                const walletResponse =  walletModel.findOne({userId: user}, {amount: 1, _id: 0});1, _id: 0});
                return walletResponse;
            } catch (error) {
                console.log(`Wallet not found. ${error}`)
            }       
        }
        return {
            getWalletById: getWalletById,
        }
    }
    
    Login or Signup to reply.
  2. I think the issue is caused by the projection syntax you are using.
    try this one

    walletModel.find(
      { userId: new ObjectId(user) },
      { projection: { amount: 1, _id: 0 } }
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search