这对mongodb来说是全新的,但我认为肯定有一些非常基本的东西我没有理解。如果我运行shell并输入db.questions.count()
,我会得到1,这是我在shell中创建的1。但如果我在我的应用程序中做同样的事情:
...
const MONGO_URL = 'mongodb://127.0.0.1:27017/';
const {MongoClient, ObjectId} = mongo;
const run = async () => {
try {
const db = await
MongoClient.connect(MONGO_URL);
const Questions = db.questions;
console.log(Questions.count());
...
我得到了Cannot read property 'count' of undefined
。为什么会这样呢?
值得注意的是,定义了db,并且URL与shell中的URL相同。另外,服务器启动得很好,所以我认为这意味着mongodb实例运行良好。
发布于 2019-03-15 08:19:08
安装mongodb npm模块。它是NodeJs的官方MongoDB客户端。
// Create a Mongo Client Instace to connect to the MongoDB Database
// and perform various functions.
const MongoClient = require( 'mongodb' ).MongoClient;
// Store the URL of your MongoDB Server
const mongoURL = "mongodb://localhost:27017/";
// Stored the name of the Database you wanna connect to.
const dbName = "testdb";
// Create a new Mongo DB client that will connect to the MongoDB Server.
const client = new MongoClient(mongoURL);
// Connect the Client to the MongoDB Server.
client.connect( (err) => {
// Error handling of some sort.
if(err) throw err;
console.log( 'connected!' );
// Connect to the database you want to manage using the dbName you
// stored earlier.
const db = client.db( dbName );
// Store the name of the collection you want to read from.
// this can be created above near the dbName.
const collectionName = "testCol"
// Connect to the collection that you stored above.
const collection = db.collection( collectionName );
// Query the MongoDB database and log the results, if any.
collection.find({}).toArray( (err, docs) => {
console.log(docs);
} );
} )
要消除newURLParser错误,只需使用
const client = new MongoClient( mongoURL, { useNewUrlParser: true } );
而不是
const client = new MongoClient(mongoURL);
这是指向MongoDB NodeJS快速入门的链接。http://mongodb.github.io/node-mongodb-native/3.1/quick-start/quick-start/
https://stackoverflow.com/questions/55173723
复制相似问题