Node.js MongoDB不会在服务器上唤醒

编程入门 行业动态 更新时间:2024-10-27 12:26:54
本文介绍了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不会在服务器上唤醒

本文发布于:2023-10-29 10:41:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1539470.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:会在   器上   Node   js   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!