我正在使用MongoDB 的node-mongodb-native驱动程序来编写一个网站.
我有一些关于如何管理连接的问题:
对所有请求只使用一个MongoDB连接是否足够?有任何性能问题吗?如果没有,我可以设置全局连接以在整个应用程序中使用吗?
如果没有,如果我在请求到达时打开一个新连接并在处理请求时关闭它是否合适?打开和关闭连接是否昂贵?
我应该使用全局连接池吗?我听说驱动程序有一个本机连接池.这是一个不错的选择吗?
如果我使用连接池,应该使用多少个连接?
还有其他我应该注意的事情吗?
我一直在阅读和阅读,但仍然对在整个NodeJs应用程序之间共享相同数据库(MongoDb)连接的最佳方式感到困惑.据我所知,应用程序启动时应该打开连接,并在模块之间重用.我目前对最佳方法的想法是server.js
(所有内容开始的主文件)连接到数据库并创建传递给模块的对象变量.连接后,模块代码将根据需要使用此变量,此连接将保持打开状态.例如:
var MongoClient = require('mongodb').MongoClient;
var mongo = {}; // this is passed to modules and code
MongoClient.connect("mongodb://localhost:27017/marankings", function(err, db) {
if (!err) {
console.log("We are connected");
// these tables will be passed to modules as part of mongo object
mongo.dbUsers = db.collection("users");
mongo.dbDisciplines = db.collection("disciplines");
console.log("aaa " + users.getAll()); // displays object and this can be used from inside modules
} else
console.log(err);
});
var users = new(require("./models/user"))(app, mongo);
console.log("bbb " + users.getAll()); // not connected at …
Run Code Online (Sandbox Code Playgroud) 我试图将数据发布到我在mLab上创建的数据库,我收到此错误但我不知道什么是错误.我也读过有关此主题的先前询问的问题,但我无法解决我的错误我是新来的.所以我在这里发布我正在尝试实现的代码,它来自本教程https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes- a07ea9e390d2.
server.js
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const db = require('./config/db');
const app = express();
const port = 8000;
app.use(bodyParser.urlencoded({extened:true}));
MongoClient.connect(db.url,(err,database) =>{
if (err) return console.log(err)
require('./app/routes')(app,{});
app.listen(port,() => {
console.log("We are live on"+port);
});
})
Run Code Online (Sandbox Code Playgroud)
db.js
module.exports = {
url : "mongodb://JayTanna:Jay12345@ds147510.mlab.com:47510/testing"
};
Run Code Online (Sandbox Code Playgroud)
index.js
const noteroutes = require('./note_routes');
module.exports = function(app,db)
{
noteroutes(app,db);
};
Run Code Online (Sandbox Code Playgroud)
note_routes.js
module.exports = function(app, db) {
app.post('/notes', (req, res) => {
const note = { …
Run Code Online (Sandbox Code Playgroud) 我试图创建一个mongo实例但是我无法访问mongodb nodejs驱动程序中的任何帮助方法.
我的mongo实例在docker中运行,端口已经打开到我的本地.
TypeError: db.createCollection is not a function
at /var/www/html/beacon/index.js:6:8
at args.push (/var/www/html/beacon/node_modules/mongodb/lib/utils.js:431:72)
at /var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:254:5
at connectCallback (/var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:933:5)
at /var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:794:11
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
Run Code Online (Sandbox Code Playgroud)
从w3schools复制...
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.createCollection("customers", function(err, res) {
if (err) throw err;
console.log("Collection created!");
db.close();
});
});
Run Code Online (Sandbox Code Playgroud)
运行时不返回任何错误,并且db对象上没有公开任何方法.
有任何想法吗?
我使用MongoDB Atlas作为我的数据库.
我正在使用angular4和loopi作为api.
我的应用程序连接到我的数据库.但是,当我尝试获取数据时,我收到此错误(我已使用dbname替换了我的dbname):
MongoError: user is not allowed to do action [find] on [dbname.$cmd]
Run Code Online (Sandbox Code Playgroud)
如果我在AWS上使用本地mongodb客户端或mongodb实例,则查询工作正常.但是,在使用地图集时,我收到此错误.
我试图编写一个有角度的应用程序,将来自全接触式API的信息作为json并将其插入到mongodb中。我可以成功获取json文件,但是当我尝试将其插入到mongodb中时,我遇到了各种错误。我解决了许多错误,但我卡在这一个。任何帮助表示赞赏。
ERROR:
MongoError {name: "MongoError", message: "docs parameter must be an array of documents", driver: true, stack: "MongoError: docs parameter must be an array of doc…(http://localhost:4200/vendor.bundle.js:71114:10)"}driver: truemessage: "docs parameter must be an array of documents"name: "MongoError"stack: "MongoError: docs parameter must be an array of documents? at Function.webpackJsonp.../../../../mongodb-core/lib/error.js.MongoError.create (http://localhost:4200/vendor.bundle.js:33916:11)? at Collection.webpackJsonp.../../../../mongodb/lib/collection.js.Collection.insertMany (http://localhost:4200/vendor.bundle.js:44864:32)? at http://localhost:4200/main.bundle.js:57:20? at Db.webpackJsonp.../../../../mongodb/lib/db.js.Db.collection (http://localhost:4200/vendor.bundle.js:49750:20)? at Object.webpackJsonp.../../../../../routes/kisiler.js.exports.kisiEkle (http://localhost:4200/main.bundle.js:54:9)? at http://localhost:4200/main.bundle.js:366:18? at Request.requested [as _callback] (http://localhost:4200/vendor.bundle.js:21598:5)? at Request.self.callback (http://localhost:4200/vendor.bundle.js:70137:22)? at Request.webpackJsonp.../../../../events/events.js.EventEmitter.emit (http://localhost:4200/vendor.bundle.js:20324:17)? at Request.<anonymous> (http://localhost:4200/vendor.bundle.js:71114:10)"__proto__: Error
at Object.../../../../mongodb-core/lib/error.js (http://localhost:4200/vendor.bundle.js:33927:24)
at …
Run Code Online (Sandbox Code Playgroud) 我正在将数据库从 Mlab 迁移到 MongoDB Atlas。我们必须将 mongodb 的 npm 版本升级到3.4.1
MongoDB atlas 数据库版本4.2.5
。
连接功能已按照此答案中所述进行了更新。但是在将 npm 版本升级到3.4.1
findOne 后,即使文档在集合中可用,findOne 查询也会返回空值。这是与 findOne 查询相关的代码部分,
db.collection('organisations').findOne({ _id: database.ObjectID(orgState) })
.then((activeOrganisation) => {
console.log(activeOrganisation);
data.activeOrganisation = activeOrganisation;
callback(null, activeOrganisation);
}, (error) => {
callback(error, null);
});
Run Code Online (Sandbox Code Playgroud)
因此我想知道数据库连接是否有问题,因此我使用运行db.serverConfig.isConnected()
,db.databaseName
和进行了测试db.listCollections().toArray()
。返回isconnected
的true
和返回的数据库名也是正确的。但db.listCollections().toArray()
返回一个空数组,这意味着我的数据库中没有不能的集合。
然后我尝试findOneAndUpdate
查询只是为了检查会发生什么。这是它的相关代码,
db.collection('users').findOneAndUpdate(
{ emails: { $elemMatch: { email: "rajitha1591@outlook.com" } } },
{ $addToSet: { unsubscribedEmails: "models" } }) …
Run Code Online (Sandbox Code Playgroud) 当我运行此代码时,它有一个错误'TypeError:db.collection不是一个函数'.如何解决此问题以及此代码中的错误.
const MongoClient = require('mongodb').MongoClient;
// Connection url
const url = 'mongodb://localhost:27017/blog';
// Connect using MongoClient
MongoClient.connect(url, (err, db) => {
const note = {
text: 'Note content text',
title: 'Note title'
};
db.collection('notes').insert(note, (err, result) => {
if (err) {
console.log('An error has occurred!')
} else {
console.log('Insert success!')
}
});
});
Run Code Online (Sandbox Code Playgroud)
我试图简单地在MongoDB
集合中插入一个条目Nodejs
.这是我的代码:
码:
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/TodoApp', (err, db) => {
if (err) {
return console.log('Unable to connect to MongoDB server');
}
console.log('Connected to MongoDB server');
db.collection('Todos').insertOne({
text: 'Something to do',
completed: false
}, (err, result) => {
if (err) {
return console.log('Unable to insert todo', err);
}
console.log(JSON.stringify(result.ops, undefined, 2));
});
db.close();
});
Run Code Online (Sandbox Code Playgroud)
当我运行代码时,它显示以下错误:
错误:
TypeError: db.collection is not a function
Run Code Online (Sandbox Code Playgroud)