这是控制器类
const Product = require('../models/product.model');
//Simple version, without validation or sanitation
exports.test = function (req, res) {
res.send('Greetings from the Test controller!');
};
exports.product_create = function (req, res) {
const product = new Product(
{
name: req.body.name,
price: req.body.price
}
);
product.save(function (err) {
if (err) {
return next(err);
}
res.send('Product Created successfully')
})
};
models/product.model.js
var mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ProductSchema = new Schema({
name: {type: String, required: true, max: 100},
price: {type: Number, required: true},
});
exports.product_details = function (req, res) {
Product.findById(req.params.id, function (err, product) {
if (err) return next(err);
res.send(product);
})
};
exports.product_delete = function (req, res) {
Product.findByIdAndRemove(req.params.id, function (err) {
if (err) return next(err);
res.send('Deleted successfully!');
})
};
exports.product_update = function (req, res) {
Product.findByIdAndUpdate(req.params.id, {$set: req.body}, function (err, product) {
if (err) return next(err);
res.send('Product udpated.');
});
};
router.put('/:id/update', product_controller.product_update);
// Export the model
module.exports = mongoose.model('Product', ProductSchema);
js这用于路由
const express = require('express');
const router = express.Router();
// Require the controllers WHICH WE DID NOT CREATE YET!!
const product_controller = require('../controllers/product.controller');
router.post('/create', product_controller.product_create);
// a simple test url to check that all of our files are communicating correctly.
router.get('/test', product_controller.test);
router.put('/:id/update', product_controller.product_update);
router.delete('/:id/delete', product_controller.product_delete);
module.exports = router;
这是应用程序js
const express = require('express');
const bodyParser = require('body-parser');
const product = require('./routes/product.route'); // Imports routes for the products
const app = express();
// Set up mongoose connection on mongoAtlas
//https://codeburst.io/writing-a-crud-app-with-node-js-and-mongodb-e0827cbbdafb
const mongoose = require('mongoose');
const dev_db_url = 'mongodb://someuser:abcd1234@ds123619.mlab.com:23619/productstutorial';
const mongoDB = process.env.MONGODB_URI || dev_db_url;
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
app.use('/products', product);
app.listen(3000,function () {
console.log("Server listen on port: 3000");
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/products', product);
所以这是该项目的代码,请添加脚本“开始”:“node app.js”。这将可以直接使用这个和更新,插入和删除数据也在这里给出了代码。
2条答案
按热度按时间dffbzjpn1#
安装程序看起来不错,但是我注意到在app.js中您可能会遗漏一些地方。我相信下面稍微修改一下的安装程序将正确地连接您的mongodb:
tquggr8v2#