SyntaxError:当使用Node JS连接到Mongo DB时,await仅在异步功能中有效

加斯顿

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

SyntaxError: await is only valid in async function

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

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}`);
谁-假面真灵魂

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

对于猫鼬:

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()混合在一起。因此,请检查以下问题或代码中不需要的部分:

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

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

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}`);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

discord.js机器人等待仅在异步功能中有效

从Node.js连接到mongodb时使用authenticationDatabase选项

使用dotnetcore连接到mongo db

使用mongoose版本(4.11.0)连接到Mongo DB

无法连接到mongo db node.js(未定义客户端)

使用Node.js连接到Mlab时出错

Javascript:SyntaxError:等待仅在异步函数中有效

使用PowerShell连接到Azure FTP时出现错误501,但在C#中有效

通过Promise将Node js连接到Mongo Atlas

module.exports SyntaxError:等待仅在异步函数中有效

module.exports SyntaxError:等待仅在异步函数中有效

Await仅在使用Node.js的异步函数中有效

使用Node JS连接到Atlas MongoDB时出错

使用docker时Go无法连接到Mongo容器

使用 node.js oracledb 连接到 Oracle DB

SyntaxError:await 仅在带有 Apify Metamorph 的异步函数中有效

即使等待位于 Node.js 中的异步函数中,如何修复“await 仅在异步函数中有效”?

Sails.js SyntaxError:await 仅在异步函数中有效

使用 mongo-spark-connector 连接到 mongodb 时出错

await 仅在异步函数 discord.js 中有效

“await 仅在异步函数中有效” discord.js

使用 mongo shell 连接到 mongodb 时遇到问题

await 总是抛出 SyntaxError: await 仅在 sequelize 的异步函数中有效

使用 MVC Node.js 时如何连接到 MongoDB?

`SyntaxError:await 仅在异步函数中有效`,同时尝试在 node rest api 中注册用户

ASYNC / AWAIT SyntaxError:await 仅在异步函数和模块的顶级主体中有效

For 循环 - SyntaxError: await 仅在异步函数中有效

获取 SyntaxError: await 仅在异步函数和模块的顶层主体中有效,同时通过 discord.js 指南工作

SyntaxError: await 仅在异步函数和模块的顶层主体中有效。不和谐,js