![](/img/trans.png)
[英]while using save() & find({}) functions in mongoose it return SyntaxError: await is only valid in async functions and the top level bodies of modules
[英]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();
在使用保存功能時它給了我錯誤等待只能在異步功能中使用我不知道如何解決它,任何幫助。
首先,您要保存 helloKitty 而不是 kittyKart,因為這里沒有像 kittyKart 這樣的對象,而且您在函數下方編寫的所有內容都將包含在函數中,包括 save,因為 save 中的 await 函數需要父異步函數。
所以這些是正確的代碼行 -
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.