如何使用Go驱动程序或Golang在Mongodb中插入JavaScript函数

huangapple go评论88阅读模式
英文:

How to insert javascritpt function in Mongodb using Go driver or Golang

问题

我在MongoDB官方网站上看到了下面的代码,用于在MongoDB中插入一个JavaScript函数。

db.system.js.save(
   {
     _id: "echoFunction",
     value : function(x) { return x; }
   }
)

链接是:https://docs.mongodb.com/manual/tutorial/store-javascript-function-on-server/

我在mongoShell中尝试了这些步骤,效果很好。
现在,我想使用Golang将JavaScript函数存储到MongoDB中。

我在gopkg.in/mgo.v2/bson包中看到了下面的结构。

// JavaScript是一个保存JavaScript代码的类型。如果Scope非空,它将被序列化为从标识符到值的映射,这些值在评估提供的代码时可以使用。
type JavaScript struct {
    Code  string
    Scope interface{}
}

这是否与我期望的相关?
请分享你的知识。

英文:

I saw the below code in mongodb official site, to insert a Javascript function in mongodb.

db.system.js.save(
   {
     _id: "echoFunction",
     value : function(x) { return x; }
   }
)

link is:
https://docs.mongodb.com/manual/tutorial/store-javascript-function-on-server/

I tried the procedures in mongoShell and it is working good.
Now, I want to store javascript function in to mongodb using golang.

I saw the below structure in gopkg.in/mgo.v2/bson package.

// JavaScript is a type that holds JavaScript code. If Scope is non-nil, it
// will be marshaled as a mapping from identifiers to values that may be
// used when evaluating the provided Code.
type JavaScript struct {
	Code  string
	Scope interface{}
}

Does it relates to what I expected?
Please share your Knowledge.

答案1

得分: 1

以下是翻译好的内容:

这是如何创建一个返回bson.JavaScript结构的函数:

func mongoNow() bson.JavaScript {
    return bson.JavaScript{
        // 在这里放入你的函数字符串
        Code: "(new Date()).ISODate('YYYY-MM-DD hh:mm:ss')"
    }
}

然后插入到你的集合中:

c := mongoSession.DB("YourDB").C("YourCollection")
err := c.Insert(
    struct{ LastSeen interface{} }{
        LastSeen: mongoNow()
    }
)

请不要忘记插入适当的import包。

英文:

Here is how First create a function that will return bson.JavaScript struct :

func mongoNow() bson.JavaScript {

    return bson.JavaScript{
      // place your function in here in string
      Code: "(new Date()).ISODate('YYYY-MM-DD hh:mm:ss')"
    }
}

And insert to your collections :

c := mongoSession.DB("YourDB").C("YourCollection")
err := c.Insert(
   struct{LastSeen interface{}}
      {  
         LastSeen: mongoNow() 
      }
)

Please do not forget to insert your appropriate import package.

huangapple
  • 本文由 发表于 2017年5月8日 14:39:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/43841262.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定