mongodb的新手,但我认为必须有一些我没有得到的非常基本的东西。如果运行外壳程序并键入db.questions.count()
,则得到1,即在外壳程序中创建的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实例运行正常。
答案 0 :(得分:1)
安装“ mongodb” npm模块。它是NodeJ的官方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/