Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript MongoClient和Express,连接成功。。。但是:TypeError:无法读取属性';收集';空的_Javascript_Node.js_Mongodb_Express - Fatal编程技术网

Javascript MongoClient和Express,连接成功。。。但是:TypeError:无法读取属性';收集';空的

Javascript MongoClient和Express,连接成功。。。但是:TypeError:无法读取属性';收集';空的,javascript,node.js,mongodb,express,Javascript,Node.js,Mongodb,Express,我试图使用MongoClient而不是mongoose。 但我很难弄明白为什么不能在我的routes文件中设置新集合 db/index.js const{MongoClient}=require('mongodb'); const MONGO_DB_NAME='moooongooo'; const MONGO_港=27017; const MONGO_URI=`mongodb://localhost:${MONGO_PORT}/${MONGO_DB_NAME}`; const MONGO_选项=

我试图使用MongoClient而不是mongoose。 但我很难弄明白为什么不能在我的routes文件中设置新集合

db/index.js

const{MongoClient}=require('mongodb');
const MONGO_DB_NAME='moooongooo';
const MONGO_港=27017;
const MONGO_URI=`mongodb://localhost:${MONGO_PORT}/${MONGO_DB_NAME}`;
const MONGO_选项={
游泳池规模:5,
useNewUrlParser:true,
useUnifiedTopology:正确
};
类连接{
构造函数(uri、选项、名称){
this.db=null;
this.uri=uri;
this.options=选项;
this.name=名称;
}
连接(){
if(this.db){
返回承诺。解决(this.db);
}否则{
返回MongoClient.connect(this.uri,this.options)。然后(client=>{
this.db=client.db(this.name);
返回这个.db;
});
}
}
}
module.exports=新连接(MONGO_URI、MONGO_选项、MONGO_DB_名称);
bin/www(节选)

/**
*找到MongoDB。
*/
const db=require('../db');
/**
*创建HTTP服务器。
*/
var server=http.createServer(app);
/**
*连接到MongoDB,然后在所有网络接口的提供端口上侦听。
*/
db.connect().then(db=>{
控制台日志(db);
监听(端口);
server.on('error',onError);
server.on('listing',onListening);
});
app.js

var express=require('express');
var path=require('path');
var cookieParser=require('cookie-parser');
var记录器=需要('morgan');
var indexRouter=require('./路由/索引');
var usersRouter=require(“./routes/users”);
var-app=express();
应用程序使用(记录器(“开发”);
使用(express.json());
use(express.urlencoded({extended:false}));
使用(cookieParser());
app.use(express.static(path.join(uu dirname,'public'));
应用程序使用(“/”,索引路由器);
app.use('/users',usersRouter);
module.exports=app;
然后我运行服务器。一切都好

服务器

> nodemon ./bin/www

[nodemon] 1.19.1
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node ./bin/www`
Db {
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  s: {
    dbCache: {},
    children: [],
    topology: NativeTopology {
      _events: [Object: null prototype],
      _eventsCount: 25,
      _maxListeners: undefined,
      s: [Object]
    },
    options: { retryWrites: true, promiseLibrary: [Function: Promise] },
    logger: Logger { className: 'Db' },
    bson: BSON {},
    readPreference: null,
    bufferMaxEntries: -1,
    parentDb: null,
    pkFactory: undefined,
    nativeParser: undefined,
    promiseLibrary: [Function: Promise],
    noListener: false,
    readConcern: undefined,
    writeConcern: undefined,
    namespace: MongoDBNamespace { db: 'moooongoooo', collection: undefined }
  },
  serverConfig: [Getter],
  bufferMaxEntries: [Getter],
  databaseName: [Getter]
}
但是当我试图向数据库发布一个新的用户对象时,我不知道。 我得到错误:
TypeError:无法读取null的属性“collection”

routes/users.js

var express=require('express');
var router=express.router();
const db=require('../db').db;
const collection=db.collection(“用户”);
路由器.post(“/”,(请求,res)=>{
collection.insertOne(请求正文,(错误,结果)=>{
如果(错误)抛出错误;
res.send(结果);
})
});
module.exports=路由器;

您可以更改app.js,如下所示,等待db连接建立,然后需要路由

const express = require('express');
const path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var app = express();

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

let db = require('./db');

this.init = async () => { 
    await db.connect(); // this line waits until db connection established


    //let indexRouter = require('./routes/index');
    let usersRouter = require('./routes/users');
    //app.use('/', indexRouter);
    app.use('/users', usersRouter);
}

this.init()



module.exports = app;

您可以按如下方式更改app.js,直到db连接建立,然后需要路由

const express = require('express');
const path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var app = express();

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

let db = require('./db');

this.init = async () => { 
    await db.connect(); // this line waits until db connection established


    //let indexRouter = require('./routes/index');
    let usersRouter = require('./routes/users');
    //app.use('/', indexRouter);
    app.use('/users', usersRouter);
}

this.init()



module.exports = app;

我只是对这里的冗余代码数量感到惊讶,使用config连接到mongo数据库只需不到5行代码,为什么要使这么简单的操作复杂化?您需要等到connect()函数返回promise。顺便说一句,尝试显式导入
集合模型
,而不要使用
db.model('users'))
我对这里的冗余代码数量感到惊讶,使用config连接到mongo数据库只需不到5行代码,为什么要使这么简单的操作复杂化?您需要等待connect()函数返回promise.btw,尝试显式导入
集合模型
,而不要使用
db.model('users'))