Ошибка синтаксиса: ожидание допустимо только в функции asyn c, при подключении к базе данных Mon go с использованием Node JS - PullRequest
1 голос
/ 13 января 2020

Я пытаюсь получить доступ к базе данных mon go, используя функцию asyn c / await в Javascript, используя приведенный ниже код. Когда я запускаю код, терминал возвращает следующую ошибку:

SyntaxError: await is only valid in async function

Ошибка сбивает меня с толку из-за моего использования "asyn c" для newFunction. Я попытался изменить расположение «asyn c» и «await», но ни одна комбинация, которую я пробовал до сих пор, не привела к успешному выполнению. Любое понимание будет очень ценится.

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

Ответы [ 2 ]

0 голосов
/ 13 января 2020

В вашем коде произошли значительные изменения, попробуйте ниже:

Для понедельника goose:

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, и они смешивают асинхронные / ожидающие с callback (). Поэтому проверьте проблемы или ненужные части вашего кода ниже:

SyntaxError: await действителен только в функции asyn c - потому что вы не можете использовать 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}`);
0 голосов
/ 13 января 2020

Ошибка правильная, так как функция не асин c. Сделайте вашу функцию обратного вызова в toArray async.

Пример

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( async function (err, result)  {
        if (err) throw err;
        theNames = await result;
        return theNames;
        db.close();
      });
    });
}
newFunction();
console.log(`Here is a list of theNames: ${theNames}`);
...