Nodejs mongodb don't woking on server

让人想犯罪 __ 提交于 2019-12-08 10:12:05

问题


On local, I installed NodeJS 9.2 and MongoDB 3.4

I using MongoDB Native Node Driver 3.0.4

My code with database

const mongo = require('mongodb').MongoClient;
const mongoose = require('mongoose');

mongo.connect('mongodb://localhost:27017/my_database', function(err, client){
    console.log(err);
    if (!err){
        var database = client.db('my_database');
        database.collection('users').find({}).toArray(function(err, docs){
            console.log(docs);
        });
    }
});

Result null for error and array users in collection

So, on server centos 7 installed nodejs 8.2, Result null for error and empty array for docs

How does it work?


回答1:


Connection

const mongoose = require('mongoose');
const URL = "mongodb://user:pass@mongo:27017/database?authSource=admin";

mongoose.connect(URL, {"server":{"auto_reconnect":true}});

var db = mongoose.connection;

db.on('error', function(err) {
    console.error('Error in MongoDB connection: ' + err);
});


db.on('connected', function() {
      console.log('Connected to MongoDB');
});

Model

You create a schema that represents a collection in your db

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const MyModel = Schema({
  foo: String
}, { collection: 'mycollection' });

module.exports = mongoose.model('MyModel', MyModelSchema);

Controller

You use this schema to execute requests to that collection

const MyModel = require('../models/mymodel');

function myFunction(req, res) {
 MyModel.find({}).exec(function(err, result){
     if(!result) return res.status(404).send();
     var array = [];
     result.map(function(data){
        array.push(data.foo);        
     });
     res.status(200).send({"mydata": array});
 });
}

module.exports = {
  myFunction
};


来源:https://stackoverflow.com/questions/49547992/nodejs-mongodb-dont-woking-on-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!