如何使用node.js,express.js和mongo db创建restful api。我需要如何为登录和注册页面编写模式,以及如何使用nodejs express js将数据与mongodb进行比较。
我是nodejs的初学者,请帮我一些例子。
答案 0 :(得分:2)
//the simple example of login//
router.post('/users/login', function (req, res) {
var users = req.app;
var email = req.body.email;
var password = req.body.password;
if (email.length > 0 && password.length > 0) {
users.findOne({email: email, password: password}, function (err, user) {
if (err) {
res.json({status: 0, message: err});
}
if (!user) {
res.json({status: 0, msg: "not found"});
}
res.json({status: 1, id: user._id, message: " success"});
})
} else {
res.json({status: 0, msg: "Invalid Fields"});
}
});
//and if you have to create schema
var db_schema = new Schema({
email: {type: String, required: true, unique: true},
password: {type: String, required: true, unique: true},
});
// define this in your db.js
var login_db = mongoose.model('your_db_name', db_schema);
return function (req, res, next) {
req.app = login_db;
next();
};