使用Node.js在Mongo DB中存储JS函数的问题 [英] Problems storing JS functions in Mongo DB with Node.js

查看:71
本文介绍了使用Node.js在Mongo DB中存储JS函数的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的JS类:

I have a simple JS class:

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

然后我使用默认值将其存储在MongoDB中Node.js驱动程序:

I then go to store it in MongoDB using the default Node.js driver:

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'

我完全迷失了这个。我的理解是MongoDB按原样存储了JS函数和属性。如果不是这样,你能推荐我如何解决这个问题吗?

I'm totally lost on this one. My understanding was that MongoDB stored both JS functions and properties as-is. If this isn't the case, can you recommend how I can work around this?

谢谢!

推荐答案

Mongo无法存储函数(代码),只能存储数据。获取您获得的原始数据并将其传递给构造函数,或者考虑像mongoose这样的ODM。

Mongo cannot store functions (code), only data. Take the raw data you get back and pass it to a constructor function, or consider an ODM like mongoose.

有一组非常具体且有限的条件,您可以以字符串形式发送mongo函数代码并在服务器上进行评估。这些内容记录在 MongoDB手册中。但是,在mongo中运行的代码的目的是支持复杂的数据查询操作,而不是为应用程序逻辑建模,这就是这个问题所要求的。应用程序逻辑位于node.js模块 .js 文件中。数据在数据库中。

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. These are documented in the MongoDB manual. 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. Application logic goes in your node.js module .js files. Data goes in the database.

这篇关于使用Node.js在Mongo DB中存储JS函数的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆