Home > Software engineering >  while using save() & find({}) functions in mongoose it return SyntaxError: await is only valid in as
while using save() & find({}) functions in mongoose it return SyntaxError: await is only valid in as

Time:05-16

const mongoose = require('mongoose');

main().catch(err => console.log(err));

async function main() { 
   await mongoose.connect('mongodb://localhost:27017/harryKart'); 
}

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

const Kitten = mongoose.model('harryKitty', kittySchema);

const harryKitty = new Kitten({ name: 'harryKittyName' });

await harryKitty.save()

const nameFind = await Kitten.find({ name: "harryKittyName" });

while using save() & find({}) functions in mongoose it return SyntaxError: await is only valid in async functions and the top level bodies of modules

CodePudding user response:

Instead of Save(), use create() function

const harryKitty = Model.create(req.body);

CodePudding user response:

You can just put the CRUD operation into an async function

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

const Kitten = mongoose.model('harryKitty', kittySchema);

const harryKitty = createKitty("harryKittyName")

const nameFind = findKitty("harryKittyName");


//create kitty
const createKitty = async(name)=>{
const newKitty = new Kitten({ name });

await newKitty.save()


return newKitty

}

//find kitty
const findKitty=async(name)=>{
return Kitten.find({ name});

}

  • Related