Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript SyntaxError:await仅在使用Node JS连接到Mongo DB时在异步函数中有效_Javascript_Node.js_Mongodb_Mongoose_Async Await - Fatal编程技术网

Javascript SyntaxError:await仅在使用Node JS连接到Mongo DB时在异步函数中有效

Javascript SyntaxError:await仅在使用Node JS连接到Mongo DB时在异步函数中有效,javascript,node.js,mongodb,mongoose,async-await,Javascript,Node.js,Mongodb,Mongoose,Async Await,我试图使用下面提供的代码,在Javascript中使用异步/等待函数访问mongo数据库。当我运行代码时,终端返回以下错误: SyntaxError: await is only valid in async function 这个错误让我感到困惑,因为我对newFunction使用了“async”。我尝试过更改“async”和“await”的位置,但迄今为止,我尝试的组合都没有成功执行。如有任何见解,将不胜感激 var theNames; var url = 'mongodb://local

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

SyntaxError: await is only valid in async function
这个错误让我感到困惑,因为我对newFunction使用了“async”。我尝试过更改“async”和“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}`);

错误是正确的,因为函数不是异步函数。使您的回调函数在
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}`);

错误是正确的,因为函数不是异步函数。使您的回调函数在
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}`);

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

猫鼬:

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));
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));
对于MongoDB驱动程序:

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

在这一行中,
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}`);

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

猫鼬:

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));
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));
对于MongoDB驱动程序:

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

在这一行中,
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}`);

它是否有效或仍然存在问题?嗨!谢谢你的登录。我刚刚尝试了你的建议,这非常有效!非常感谢你的帮助和非常有用的评论!它是否有效或仍然存在问题?嗨!谢谢你的登录。我刚刚尝试了你的建议,这非常有效!非常感谢你的帮助和支持或者是非常有用的评论!