我正在學習 MongoDB 我已經學會了如何處理 mongo 提供的所有資料型別。但我被困在 JavaScript 上。我已經設法將 JavaScript 函式存盤在檔案中。但是當我運行那個函式時,我什么也沒得到。
我在終端中使用 mongo shell。
在 MongoDB 中插入函式的腳本。
db.Test.insertOne({functiontest:function(){return "Hello";}});
運行此命令后
db.Test.find();
我得到了這個輸出
{ "_id" : ObjectId("618d4096dc79465b4196551b"), "functiontest" : { "code" : "function(){return \"Hello\";}" } }
運行此命令后
db.Test.find({functiontest:{$type:"javascript"}},{"functiontest.code":1});
我得到了這個奇怪的輸出 我以為這個輸出會給我功能,但我得到了這個。
{ "_id" : ObjectId("618d4096dc79465b4196551b") }
我也試過用管道運行這個函式,但這只給了我物件 ID。
db.Test.aggregate([{$match:{functiontest:{$type:"javascript"}}},{$project:{"codeMe":"$functiontest.code()"}}]);
uj5u.com熱心網友回復:
存盤在用戶集合中的 Javascript 存盤為字串。
MongoDB 內部使用 BSON 進行存盤,參見https://bsonspec.org/spec.html,其中定義了 javascript 代碼型別的內容為“字串”:
| "\x0D" e_name 字串 JavaScript 代碼
為了演示,我將一個檔案插入到一個新集合中:
db.Test.insertOne({_id:"myid",functiontest:function(){return "Hello";}});
來自 bash shell:
% mongodump -d test -c Test
2021-11-12T01:31:33.817-0800 writing test.Test to dump/test/Test.bson
2021-11-12T01:31:33.818-0800 done dumping test.Test (1 document)
% xxd dump/test/Test.bson
00000000: 4100 0000 025f 6964 0005 0000 006d 7969 A...._id.....myi
00000010: 6400 0d66 756e 6374 696f 6e74 6573 7400 d..functiontest.
00000020: 1c00 0000 6675 6e63 7469 6f6e 2829 7b72 ....function(){r
00000030: 6574 7572 6e20 2248 656c 6c6f 223b 7d00 eturn "Hello";}.
00000040: 00
要打破第二個欄位的十六進制:
0d - this identifies the javascript code type
66756e6374696f6e7465737400 null-terminated field name "functiontest"
1c000000 - length = 28 btyrd
66756e6374696f6e28297b72657475726e202248656c6c6f223b7d00 - string 'function(){return "Hello";}'
該字串沒有什么特別之處,除了它是由0x0d而不是引入的0x02。
您使用的 REPL 實際上沒有顯示原始 BSON 的方法,因此當您查詢該檔案時,驅動程式需要將其轉換為其他形式。JSON 沒有用于代碼的資料型別(為了好玩,請嘗試運行JSON.stringify({fun:function(){}}).
使用 C 驅動程式的舊版 mongo shell 將通過放入具有code欄位名稱的物件來將該代碼型別轉換為 JSON 。
使用 Node.JS 驅動程式的新 mongosh shell 將創建Code該類的一個實體,因此該物件如下所示:
{ _id: 'myid', functiontest: Code("function(){return "Hello";}") }
這仍然允許您訪問字串.code:
> db.Test.findOne().functiontest.code
function () {
return "Hello";
}
Both of those representations were done by the driver on the client side, so neither one exists on the server, and thus the projection operators can't see them.
Assuming that you are not planning on running your application in the mongo shell, you will probably want to experiment with the driver you actually plan to use to see how this string will be passed back to you.
The bottom line here is the "code" is actually stored as a string, and you will need to use whichever method you prefer for executing string as code.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/360072.html
標籤:javascript MongoDB 猫鼬 类型
上一篇:洗掉一個貓鼬問題快遞和節點
