如何使用node.js从猫鼬模型中获取数据并与mvc等变量一起存储



下面的代码是PHP中的示例MVC框架代码。我需要与节点相同的过程.js猫鼬也是如此。

我正在使用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进程一样使用。请对此提出建议。

假设您在猫鼬中有用户模式,它应该充当模型

// 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

最新更新