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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.