本文介绍了Node.js MongoDB不会在服务器上唤醒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在本地,我安装了NodeJS 9.2和MongoDB 3.4
On local, I installed NodeJS 9.2 and MongoDB 3.4
我使用的是MongoDB本机节点驱动程序3.0.4
I using MongoDB Native Node Driver 3.0.4
我的数据库代码
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); }); } });结果null表示集合中的错误和数组用户
Result null for error and array users in collection
因此,在服务器centos 7上安装了nodejs 8.2,结果null表示错误,空数组表示docs
So, on server centos 7 installed nodejs 8.2, Result null for error and empty array for docs
它如何工作?
推荐答案连接
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'); });型号
您创建一个表示数据库中集合的模式
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);控制器
您使用此架构执行对该集合的请求
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 };更多推荐
Node.js MongoDB不会在服务器上唤醒
发布评论