2014-08-27 54 views
3

我是服务器端javascipt的新手。我已经开始与mean.io.我最近几天对nodejs,express,mongodb有了一些了解。我有我的mean.io应用程序,但我不知道连接到mongodb并从我的js文件中查询它的正确方法。
有没有可以帮助我使用我的服务器端JavaScript文件中的mongodb的指南/博客?
我只需要存储一些数据mongodb并在稍后的时间点读取。如何通过mean.io使用MongoDB

+1

向我们展示您到目前为止所拥有的。 – Jordonias 2014-08-27 15:42:55

+0

我刚刚在mean.io中创建了doc中的meanio应用程序。我解析一个rss提要。我想将这些数据存储到mongodb中。 – Mady 2014-08-27 16:37:14

+1

这里有多个教程,你有没有打扰谷歌搜索? – 2014-08-28 00:28:18

回答

3

我找不到与mean.io有关的链接,但是下面的链接帮助我开始使用了mean.io.

http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/
https://www.youtube.com/watch?v=AEE7DY2AYvI
https://www.youtube.com/watch?v=5e1NEdfs4is

编辑:
这几天我一直在努力,并通过测试&学习我能得到的东西为我工作。到现在为止,我会分享我所知道的。

  • 所以mean.io使用mongoose ODM连接到mongodb。
  • mean.io会自动连接到您的数据库。您可以在development.jsdb: 'mongodb://localhost/myDB'中配置数据库名称。所以你不必担心连接到mongoDB。您只需要使用mongod启动mongoDB。

如何使用猫鼬?

要使用mongoose连接到mongoDB,您需要构建模式。您可以在myApp/app/models目录中这样做,因为它们代表模型。

样品模型文件user.js

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 
var userSchema = new Schema({ 
    name: String, 
    email: String, 
    DOB : Date, 
    address: { 
       house_no: String, 
       street: String 
      } 
}); 

module.exports = mongoose.model('tbl_user',userSchema); 

注: - tbl_user将被存储在DB tbl_userS

如何将数据保存到mongoDB?

通常会在控制器中对数据库执行save。下面我已经展示了如何做到这一点。
要使模型可用于所有控制器,需要在server.js中编写这段代码,以便在服务器启动期间注册所有模型。或者,使用require('tbl_user')导入单个模型。

Server.js: -

var models_path = __dirname + '/app/models'; 
    var arrFiles = fs.readdirSync(models_path); 
    arrFiles.forEach(function(file){ 
     if(file.indexOf('.js') > 0){ 
      require(models_path + '/' + file); 
     } 

    }); 

控制器代码myApp/app/controllers/myController.js

var mongoose = require('mongoose'); 
var jsonEntry = {'name':'Mady', 'email':'[email protected]', 'address':{'house_no':12N, 'stree':'abc'}}; 
var User = mongoose.model('tbl_user'); 
var user = new User(jsonEntry); 
user.save(); 

上面的代码将创建和更新tbl_users集合在MongoDB中。

3

默认情况下,您应该看到您的mongodb中有一个mean-dev集合。我认为熟悉mongo的最好方法就是围绕代码进行游戏(例如文章包)。在/packages/article/system/内部,您将看到博客示例的工作原理。

这对我很好。

+0

相关的信息,现在它是'meanStarter'包 – timelf123 2016-12-08 20:17:07