简体   繁体   中英

while using save function in mongoose it return SyntaxError: await is only valid in async functions and the top level bodies of modules

const mongoose = require('mongoose');
main().catch(err => console.log(err));
async function main() {
  await mongoose.connect('mongodb://localhost:27017/lakshKart');
}   

const kittySchema = new mongoose.Schema({
  name: String
});

kittySchema.methods.speak = function speak() {
  const greeting = "Meow name is " + this.name;
  console.log(greeting);
};

const shittyKart = mongoose.model('kittyKart', kittySchema);
const helloKitty = new shittyKart({ name: 'helloKitty' });
await kittyKart.save();

while using save function it is giving me error await can only be used in asyn function I don't know how to resolve it, any help.

Firstly you want to save helloKitty but not kittyKart because there is no object like kittyKart here, also everything that you have written below the function will be included inside the function including the save because await function in save wants a parent async function.

So these are the correct lines of code here-

const mongoose = require('mongoose');
main().catch(err => console.log(err));
async function main() {
  await mongoose.connect('mongodb://localhost:27017/lakshKart');
  const kittySchema = new mongoose.Schema({
    name: String
  });
  
  kittySchema.methods.speak = function speak() {
    const greeting = "Meow name is " + this.name;
    console.log(greeting);
  };
  
  const shittyKart = mongoose.model('kittyKart', kittySchema);
  const helloKitty = new shittyKart({ name: 'helloKitty' });
  await helloKitty.save();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM