-2

In a Mongo shell script I need to read a file to delete documents by _id but I can't import the FileReader library.

I launch script from bash to do simple find() and it works:

mongosh --host xxx --port 27017 --username xxx --password xxx --eval "var country='$country';var file='$inputDataFile'" --file scriptFile.js

But whenever I try to import a library in the js it shows the error:

TypeError: Cannot assign to read only property 'message' of object 'SyntaxError: 
'import' and 'export' may appear only with 'sourceType

The same js file I call from nodejs and the import is correct.

Right now I do the deletion of _ids contained in a file using nodejs. I would like to find a way to use Mongo shell script for all my queries

TomYJerry
  • 1
  • 2
  • I don't think you can import external files within Mongo's internal Javascript runtime…! – deceze Sep 11 '22 at 11:35
  • 1
    How do you import the library? It should work, see [Include External Files and Modules in Scripts](https://www.mongodb.com/docs/mongodb-shell/write-scripts/require-external-modules/) – Wernfried Domscheit Sep 11 '22 at 12:49
  • @deceze, why do you think so? It was even possible in the old legacy shell: [load()](https://www.mongodb.com/docs/v4.4/reference/method/load/#mongodb-method-load) – Wernfried Domscheit Sep 11 '22 at 12:56
  • I have not used load() because in the examples it is used when you are logged in mongo shell, mine is launched in an automatic bash process and I have read that --file is used – TomYJerry Sep 12 '22 at 14:58

1 Answers1

0

I managed to solve my problem with the help of Include External Files and Modules in Scripts

  1. Create package.json in the same directory as your js
  2. Add the necessary libraries to package.json
  3. Install libraries
  4. Use require to import it

Code

var fs = require('fs');
console.log(country)
console.log(file)
db = db.getSiblingDB('mongotest')

const allFileContents = fs.readFileSync(file, 'utf-8');
var lines = allFileContents.split("\r")

for (var i = 0; i < lines.length; i++) {
  const user = JSON.parse(lines[i]);
  var userId = user._id
  if (!(userId instanceof ObjectId)) {
    userId = new ObjectId(userId);
  }
  db.userChat.deleteOne({ _id: userId })
}

Thanks for your help

Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
TomYJerry
  • 1
  • 2