在 mongoose 中使用 save() 和 find({}) 函数时,它返回语法错误:await 仅在异步函数和模块的顶层主体中有效

问题描述 投票:0回答:3
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" });

在 mongoose 中使用 save() 和 find({}) 函数时,它返回语法错误:await 仅在异步函数和模块的顶层主体中有效

node.js mongoose mongodb-query mongoose-schema mongoose-populate
3个回答
0
投票

使用 create() 函数代替 Save()

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


0
投票

您可以将 CRUD 操作放入异步函数中

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

}


0
投票

这是 ES 和 Common JS (CJS) 的问题。我找到了两个解决方案:

  1. 一种快速解决方法,避免使用
    await
    或将其包装在多余的
    async
    函数中
  2. 另一个是解决ES / CJS实际问题的东西。如今,ES 在服务器端开发中被更频繁地使用,因此我认为额外一分钟的阅读/实现是值得的。

常见 JS 的快速解决方法

// rest of your code here

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

try 
{
    harryKitty.save()
    console.log('Saved successfully!')
}
catch (err)
{
    console.log('Unable to save')
}

实际解决方案

您可能正在学习使用 Common JS 的旧教程。 Common JS 使用

const mongoose = require('mongoose')
而不是
import mongoose from 'mongoose'
,因为 Common JS 模块是同步加载的。后一个
import
语句使用“ECMAScript 模块”标准,该标准支持
await
函数作为“模块主体的顶层”。

因此,如果您将所有

require
语句更改为
import
, 语句,然后将
type: 'module'
添加到父文件夹中的 package.json 文件中(见下文),那么原始
await harryKitty.save();
应该像原来一样工作有它。它对我有用。

// package.json
{
  "type": "module"
}

有关 CJS / ES 模块的更多信息,请参阅 this StackOverflow 答案我发现非常有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.