【问题标题】:while using save function in mongoose it return SyntaxError: await is only valid in async functions and the top level bodies of modules在 mongoose 中使用 save 函数时,它返回 SyntaxError: await 仅在异步函数和模块的顶层主体中有效
【发布时间】:2022-06-22 12:02:40
【问题描述】:
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();

使用保存功能时出现错误等待只能在异步功能中使用 不知道怎么解决,求大神帮助。

【问题讨论】:

  • 上面的代码调用kittyKart.save,但我相信你想要的对象是shittyKarthelloKitty
  • 试过了,但它给出了相同的 SyntaxError: await 仅在异步函数和模块的顶层主体中有效
  • 澄清一下,您尝试了await helloKitty.save(),但它给了您这个错误?

标签: node.js mongodb mongoose async-await mongoose-web-server


【解决方案1】:

首先,您要保存 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();
}

【讨论】:

    猜你喜欢
    • 2021-11-04
    • 1970-01-01
    • 2022-01-17
    • 2021-08-13
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    相关资源
    最近更新 更多