Tom3652
Tom3652

Reputation: 2967

$nin not working mongodb Atlas trigger Node JS

I have the following code in my Atlas trigger function :

  const existings = await test_collection.find().toArray();
  var ids = [];
  
  for (let i = 0; i < existings.length; i++) {
    ids.push(existings[i]._id);
  }

  console.log("Existing ids : ", ids);
  const value = await user_collection.find({"_id": {$nin: ids}}).sort({quantity: -1}).limit(1);
  console.log("Value is : ", JSON.stringify(value));

The logs are showing this :

Logs:
[
  "Existing ids :  vfLGh8QVOsbmz1,F7Mqe1YwH5fsV83",
  "Value is :  {}",
]

The python equivalent that is actually working :

 def test(self):
        test = self.db.test.find()
        ids = []
        for t in test:
            ids.append(t["_id"])
        print(f"Existing ids : {ids}")
        value = self.db.users.find({"_id": {"$nin": ids}}).sort("quantity", pymongo.DESCENDING).limit(1)
        print(f"Value is : {value[0]}")

And python logs :

Existing ids : ['vfLGh8QVOsbmz1', 'F7Mqe1YwH5fsV83']
Value is : Value is : {'_id': '6GzgNoZFR2H7hfdzI3', 'username': 'test3'}

I have tried without the sort operator to be sure the issue would come from $nin, i have the same empty output without the sort

Upvotes: 1

Views: 87

Answers (1)

nicover
nicover

Reputation: 2643

You need to add the toArray() method after the limit(1) to convert the value and to not get a cursor.

This look like :

const value = await user_collection.find({"_id": {$nin: ids}}).sort({quantity: -1}).limit(1).toArray();

and your value const should have the result.

Upvotes: 1

Related Questions