【问题标题】:How to connect to mongodb via mongoose in nodejs如何通过nodejs中的猫鼬连接到mongodb
【发布时间】:2019-05-25 16:36:42
【问题描述】:

controller/product.controller.js 这是控制器类

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);

product.route.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;

app.js 这是app.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);

这是项目的代码,请添加脚本“start”:“node app.js”。这样就可以直接使用这个和更新、插入和删除数据了,这里也给出了代码。

【问题讨论】:

  • 您好@pasan,所以问题是您在连接mongodb时遇到问题,您能否也分享错误跟踪,人们会在看到错误跟踪时更好地知道。

标签: reactjs mongodb mongoose


【解决方案1】:

设置看起来不错,但是我注意到您可能在 app.js 中遗漏了几点。我相信以下稍作修改的设置将正确连接您的 mongodb:

const mongoose = require('mongoose');
const express = require('express');
var cors = require('cors');
const bodyParser = require('body-parser');
const product = require('./routes/product.route'); // Imports routes for the products

const API_PORT = 3000;
const app = express();

app.use(cors());


// Set up mongoose connection on mongoAtlas
//https://codeburst.io/writing-a-crud-app-with-node-js-and-mongodb-e0827cbbdafb
const dev_db_url = 'mongodb://someuser:abcd1234@ds123619.mlab.com:23619/productstutorial';

// connects our back end code with the database
mongoose.connect(process.env.MONGODB_URI || dev_db_url, { useNewUrlParser: true });

let db = mongoose.connection;

db.once('open', () => console.log('connected to the database'));

// checks if connection with the database is successful
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

// bodyParser, parses the request body to be a readable json format
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());


// append /api for our http requests
app.use('/product', product);

// launch our backend into a port
app.listen(API_PORT, () => console.log(`LISTENING ON PORT ${API_PORT}`));

【讨论】:

    猜你喜欢
    • 2016-04-29
    • 2020-04-03
    • 2018-10-30
    • 2020-03-26
    • 2021-06-01
    • 2016-07-02
    • 2014-12-28
    • 2019-01-12
    相关资源
    最近更新 更多