简体   繁体   中英

How to get data from mongoose model and store with variable like mvc using node.js

Here below code is sample MVC framework code in PHP. I need same process as like in node.js with mongoose also.

I'm using Node.js, MongoDB, REST API development.

controller file:

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

model file

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

In node.js need to use as like MVC PHP process. Kindly suggest on this.

Lets say you have user schema in mongoose which should act as model

// 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();
    });
};

Ref: http://mongoosejs.com/docs/index.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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