[英]Mongo shell script - How to use libraries?
在 Mongo shell 腳本中,我需要讀取文件以按 _id 刪除文檔,但我無法導入 FileReader 庫。
我從 bash 啟動腳本來執行簡單的 find() 並且它可以工作:
mongosh --host xxx --port 27017 --username xxx --password xxx --eval "var country='$country';var file='$inputDataFile'" --file scriptFile.js
但是每當我嘗試在 js 中導入庫時,它都會顯示錯誤:
TypeError: Cannot assign to read only property 'message' of object 'SyntaxError:
'import' and 'export' may appear only with 'sourceType
我從 nodejs 調用的同一個 js 文件並且導入是正確的。
現在我使用nodejs刪除文件中包含的_ids。 我想為我的所有查詢找到一種使用 Mongo shell 腳本的方法
我設法在腳本中包含外部文件和模塊的幫助下解決了我的問題
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
代碼
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 })
}
謝謝你的幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.