簡體   English   中英

在node.js中從MongoClient執行服務器端功能

[英]Execute a server-side function from MongoClient in node.js

我已經在MongoDB服務器上創建了一組函數,希望可以在nodejs腳本中從MongoClient使用這些MongoClient 所有 的的 文件我讀過告訴我如何做到這一點,但是從外殼只有它似乎。

它在外殼中通常如何工作:

mongo database my.script.js
mongo
> use database
> db.loadServerScripts()
> add("This is a string taken in by the add function I just loaded")

這是我嘗試/研究過的(注意CoffeeScript):

MongoClient = require('mongodb').MongoClient

MongoClient.connect 'mongodb://127.0.0.1:27017/database', (e, db) ->
    console.log db.eval              #Function, but not sure what to call with
    console.log db.runCommand        #undefined
    console.log db.loadServerScripts #undefined
    console.log db.load              #undefined
    console.log db.command           #Function, but not sure what to call with
    console.log db.add               #this is one of my custom functions

希望MongoClient可以做到這一點。 如果可以管理腳本,似乎可以使用eval() ,但到目前為止,這仍然是困難的部分。 另外,我想我可以縮小函數並通過eval()運行這些eval() ,但我不想這樣做。

您可以使用eval (看起來您不需要首先加載任何函數,load命令僅是使這些函數可從Shell使用):

db.eval('add("This is a string taken in by the add function I just loaded")', function(err, result) {
  ...
});

或者,如果您想在傳遞參數時更加靈活:

db.eval('function(x) { return add(x); }', [ ARG ], function(err, result) { ... });

(似乎您不能只使用'add'作為第一個參數,您需要先將其包裝在匿名函數中,但我可能會遺漏某些東西...)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM