Home > Software engineering >  Find a document using multiple fields mongodb
Find a document using multiple fields mongodb

Time:11-01

I want to add a trade to my collection of trades only if a trade doesn't exist in the collection.

Here is my problem : the function findPosition seems to find some trades even tough my collection is empty. Therefore, no new trades are added to my collection.

Here is the code :

async function createPostion(params, uid){
  let position = new OpenPositionModel({
    uid : uid,
    symbol : params.symbol,
    entryPrice: params.entryPrice
  });
  return position.save();
}

async function findPosition(uid, symbol, entryPrice){
  return OpenPositionModel.findOne({
    $and: [
        {uid: uid},
        {symbol: symbol},
        {entryPrice: entryPrice}
    ]
  });
}

async function createNewPostion(params, uid){
  let res = findPosition(uid, params.symbol, params.entryPrice);
  if(!res){
    createPostion(params, uid);
  }
}

I have tried to use the $and operator to make sure a trade is found by the uid of the trader, the symbol and the entryPrice.

If nothing is found in a collection my cursor should by null right?

CodePudding user response:

You should wait for the Promise returned by findPosition to be resolved, within createNewPosition:

async function createNewPostion(params, uid){
  let res = await findPosition(uid, params.symbol, params.entryPrice);
  if(!res){
    createPostion(params, uid);
  }
}
  • Related