SyntaxError:当使用Node JS连接到Mongo DB时,await仅在异步函数中有效 [英] SyntaxError: await is only valid in async function, When connecting to Mongo DB using Node JS

查看:141
本文介绍了SyntaxError:当使用Node JS连接到Mongo DB时,await仅在异步函数中有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用下面提供的代码在Javascript中使用async/await函数访问mongo数据库.当我运行代码时,终端返回以下错误:

I am trying to access a mongo database using an async / await function in Javascript using the code provided below. When I run the code, the terminal returns the following error:

SyntaxError: await is only valid in async function

由于我对newFunction使用异步",因此错误令我感到困惑.我尝试过更改异步"和等待"的位置,但是到目前为止,我没有尝试过的任何组合都无法成功执行.任何见识将不胜感激.

The error is confusing to me, because of my use of "async" for newFunction. I have tried changing the location of "async" and "await," but no combination that I have tried so far has yielded successful execution. Any insight would be very much appreciated.

var theNames;
var url = 'mongodb://localhost:27017/node-demo';

const newFunction = async () => {
      MongoClient.connect(url, function (err, db) {
      if (err) throw err;
      var dbo = db.db("node-demo");
      //Find the first document in the customers collection:
      dbo.collection("users").find({}).toArray(function (err, result) {
        if (err) throw err;
        theNames = await result;
        return theNames;
        db.close();
      });
    });
}

newFunction();
console.log(`Here is a list of theNames: ${theNames}`);

推荐答案

您的代码有重大更改,请尝试以下操作:

There are significant changes in your code, Please try below :

猫鼬:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let theNames;
let url = 'mongodb://localhost:27017/node-demo';

const usersSchema = new Schema({
    any: {}
}, {
    strict: false
});

const Users = mongoose.model('users', usersSchema, 'users');
const newFunction = async () => {
    let db = null;
    try {
        /** In real-time you'll split DB connection(into another file) away from DB calls */
        await mongoose.connect(url, { useNewUrlParser: true });
        db = mongoose.connection;
        let dbResp = await Users.find({}).limit(1).lean() // Gets one document out of users collection. Using .lean() to convert MongoDB documents to raw Js objects for accessing further.
        // let dbResp = await Users.find({}).lean(); - Will get all documents.
        db.close();
        return dbResp;
    } catch (err) {
        (db) && db.close();
        console.log('Error at newFunction ::', err)
        throw err;
    }
}
newFunction().then(res => console.log('Printing at calling ::', res)).catch(err => console.log('Err at Calling ::', err));

对于MongoDB驱动程序:

const MongoClient = require('mongodb').MongoClient;

const newFunction = async function () {
    // Connection URL
    const url = 'mongodb://localhost:27017/node-demo';
    let client;

    try {
        // Use connect method to connect to the Server
        client = await MongoClient.connect(url);
        const db = client.db(); // MongoDB would return client and you need to call DB on it.
        let dbResp = await db.collection('users').find({}).toArray(); // As .find() would return a cursor you need to iterate over it to get an array of documents.
        // let dbResp = await db.collection('users').find({}).limit(1).toArray(); - For one document
        client.close();
        return dbResp;
    } catch (err) {
        (client) && client.close();
        console.log(err);
        throw err
    }
};
newFunction().then(res => console.log('Printing at calling ::', res)).catch(err => console.log('Err at Calling ::', err));

开发人员常常会对async/await&他们确实将async/await与callback()混合在一起.因此,请在下面检查问题或代码中不需要的部分:

Often dev's get confused with the usage of async/await & they do mix-up async/await's with callback()'s. So check the issues or not needed parts of your code below :

SyntaxError:await仅在异步函数中有效-是因为您不能在async function之外使用await.

在此行dbo.collection("users").find({}).toArray(function (err, result) {-由于必须使用await,因此必须具有async功能.

At this line dbo.collection("users").find({}).toArray(function (err, result) { - It has to be async function since await is being used in it.

var theNames; // There is nothing wrong using var but you can start using let.
var url = 'mongodb://localhost:27017/node-demo';

const newFunction = async () => {
      MongoClient.connect(url, function (err, db) {
      if (err) throw err;
      var dbo = db.db("node-demo");  // You don't need it as you're directly connecting to database named `node-demo` from your db url.
      //Find the first document in the customers collection:
      /** If you create a DB connection with mongoose you need to create schemas in order to make operations on DB.
          Below syntax goes for Node.Js MongoDB driver. And you've a mix n match of async/await & callbacks. */
      dbo.collection("users").find({}).toArray(function (err, result) { // Missing async keyword here is throwing error.
        if (err) throw err;
        theNames = await result;
        return theNames;
        db.close(); // close DB connection & then return from function 
      });
    });
}

newFunction();
console.log(`Here is a list of theNames: ${theNames}`);

这篇关于SyntaxError:当使用Node JS连接到Mongo DB时,await仅在异步函数中有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆