简体   繁体   English

使用Node.js在Mongo DB中存储JS函数的问题

[英]Problems storing JS functions in Mongo DB with Node.js

I have a simple JS class: 我有一个简单的JS类:

var User = function(id){
    this._id = id;
    this.sayHello = function (){
        return "hello";
    }
}

I then go to store it in MongoDB using the default Node.js driver: 然后我使用默认的Node.js驱动程序将其存储在MongoDB中:

users.insert(new User(1));

Finally, I retrieve the user, and try to execute the function: 最后,我检索用户,并尝试执行该功能:

users.findOne({_id:1}, function(err, item) {
    console.log("Say hello: " + item.sayHello());
});

I receive the following error, which is really confusing: 我收到以下错误,这真的令人困惑:

    throw err;
          ^
TypeError: Object #<Object> has no method 'sayHello'

I'm totally lost on this one. 我完全迷失在这一个。 My understanding was that MongoDB stored both JS functions and properties as-is. 我的理解是MongoDB按原样存储了JS函数和属性。 If this isn't the case, can you recommend how I can work around this? 如果不是这样,你能推荐我如何解决这个问题吗?

Thanks! 谢谢!

Mongo cannot store functions (code), only data. Mongo无法存储函数(代码),只能存储数据。 Take the raw data you get back and pass it to a constructor function, or consider an ODM like mongoose. 获取您获得的原始数据并将其传递给构造函数,或者考虑像mongoose这样的ODM。

There are a very specific and limited set of conditions wherein you can send mongo function code in string form and have it evaluated on the server. 有一组非常具体和有限的条件,您可以以字符串形式发送mongo功能代码并在服务器上进行评估。 These are documented in the MongoDB manual . 这些内容记录在MongoDB手册中 However, the purpose of that code running inside mongo is to support sophisticated data query operations, not to model application logic, which is what this question is asking about. 但是,在mongo中运行的代码的目的是支持复杂的数据查询操作,而不是为应用程序逻辑建模,这就是这个问题所要求的。 Application logic goes in your node.js module .js files. 应用程序逻辑位于node.js模块.js文件中。 Data goes in the database. 数据进入数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM