0

下面的代码是PHP中的示例MVC框架代码。我也需要和node.js一样的进程,就像使用猫鼬一样。如何从mongoose模型获取数据并使用node.js存储变量,如mvc

我正在使用Node.js,MongoDB,REST API开发。

控制器文件:

<?php 
class Myclass { 
public function store_users() { 
    //get the data from model file 
    $country = $this->country->get_country_details($country_id); 
    //After getting data do business logic 
} 
} 

模型文件

<?php 
class Mymodel { 
public function get_country_details($cid) { 
    $details = $this->db->table('country')->where('country_id',$id); 
    return $details; 
} 
} 

在node.js中需要像MVC PHP过程中使用。请在此建议。

+0

使用** **的RESTify,** **猫鼬,智威汤逊与** restify-jwt **创建一个应用程序。在谷歌搜索。你会发现许多博客显示实施。在那里它将被正确地提及关于猫鼬模型和restapi – Priya

+0

@Priya,已经基​​于博客基于谷歌搜索的例子开发了API。在node.js中已经分离了模型,控制器,路由。所以在这里,我需要始终使用猫鼬查询方法(每次需要编写查询)从模型文件中获取数据。所以我需要使用模型函数来获取所有控制器的数据,所以需要针对此解决方案。 –

+0

没有像'mongoose query method'这样的方法。但总是可以使用猫鼬预定义的方法,如find,findOne,exec,distinct,aggregate,findById,count等。 api.html#model_Model – Priya

回答

0

比方说你有猫鼬,用户模式应该作为模范作用

// userModel.js 
var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 

var user = new Schema({ 
    name: { type: String, required: true }, 
    dob: { type: Date }, 
    email: { type: String, required: true, unique: true, lowercase: true}, 
    active: { type: Boolean, required: true, default: true} 
}, { 
    timestamps: { 
    createdAt: 'created_at', 
    updatedAt: 'updated_at' 
    } 
}); 

var userSchema = mongoose.model('users', user); 
module.exports = userSchema; 
// userController.js 
var User = require('./userModel'); 

exports.getUserByEmail = function(req, res, next) { 
    var email = req.param.email; 
    User.findOne({ email: email }, function(err, data) { 
     if (err) { 
      next.ifError(err); 
     } 
     res.send({ 
      status: true, 
      data: data 
     }); 
     return next(); 
    }); 
}; 

编号:http://mongoosejs.com/docs/index.html

+0

感谢您的回答。还有一件事我可以在文件的任何地方使用这个公共功能 –

+0

抱歉没有公开。您可以直接导出方法或创建一个对象并导出。像'var user = {getUserByEmail:getUserByEmail}; module.exports = user;'公共函数不过是暴露的范围变量。私人不能暴露。在nodejs中学习'exports'的使用 – Priya

相关问题