0

以下のコードはPHPのサンプルMVCフレームワークコードです。 mongooseもnode.jsと同じプロセスが必要です。mongooseモデルからデータを取得し、node.jsを使用してmvcのような変数を格納する方法

私はNode.js、MongoDB、REST API開発を使用しています。

コントローラファイル:Node.jsので

<?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; 
} 
} 

はMVC PHPプロセス等として使用する必要があります。親切にこれをお勧めします。

+0

使用** restify **、**マングース**、JWTと** restify-jwt **を使用してアプリを作成します。 Googleで検索してください。実装を示す多くのブログがあります。それは適切にマングースモデルとrestapiについて述べるでしょう – Priya

+0

@プリヤ、既にGoogleの検索に基づくブログの例に基づいてAPIを開発しました。 node.jsではすでにモデル、コントローラ、ルートが分離されていました。だからここで私はモデルファイルからmongooseのクエリメソッド(毎回クエリを書く必要がある)を使ってデータを取得する必要があります。だから私はすべてのコントローラでデータを取得するためにモデル関数を使う必要があるので、これを解決する必要があります。 –

+0

「mongoose query method」のようなメソッドはありません。しかし、いつもあなたは 'find'、' findOne'、 'exec'、' distinct'、 'aggregate'、' findById'、 'count'などのmongooseの定義済みメソッドを使うことができます。ref:http://mongoosejs.com/docs/ 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

回答ありがとうございます。もう1つはファイル内のどこでもこの公開関数を使用できます –

+0

申し訳ありません。メソッドを直接エクスポートしたり、オブジェクトを作成してエクスポートしたり、エクスポートすることができます。 'var user = {getUserByEmail:getUserByEmail} 'のように。 module.exports = user; '公開関数は公開されたスコープ変数だけです。露出できないプライベート。 nodejsの 'exports'の使い方を学んでください – Priya

関連する問題