如何在 Mongoose 中保存与等待?

a2mppw5e  于 2022-11-13  发布在  Go
关注(0)|答案(3)|浏览(173)

下面的代码可以工作,但我只想使用async/await,所以我的问题是:我怎么能把

cat.save().then(() => console.log('Saved in db'));

改用await
我使用mongoose.connection.once()的原因是只在MongoDB连接时发送命令。如果这也可以使用await,那么它将真的很棒=)

import mongoose from 'mongoose';
import { connectDb } from './modules/connectDb';
const { Schema } = mongoose;
const catSchema = new Schema({ name: String });
    
(async () => {
  connectDb('testDB');

  mongoose.connection.once('open', () => {
    console.log('MongoDB is connected');

    mongoose.connection.db.listCollections().toArray(function (err, names) {
      console.log(names);
    });

    const catModel = mongoose.model('testColl', catSchema);

    const cat = new catModel({ name: 'Zildjian' });
    cat.save().then(() => console.log('Saved in db'));
  });
})();

连接数据库

import mongoose from 'mongoose';
import { strict as assert } from 'assert';
import { readToml } from './readToml';

const db = readToml('./config/database.toml');

export function connectDb(
  database: string = db.database,
  uri: string = db.uri,
  username: string = db.username,
  password: string = db.password,
) {
  assert(typeof uri === 'string');
  assert(typeof database === 'string');
  assert(typeof username === 'string');
  assert(typeof password === 'string');

  const URI = `mongodb+srv://${username}:${password}@${uri}/${database}?retryWrites=true&w=majority`;

  try {
    mongoose.connect(URI);
  } catch (err) {
    console.error(err);
  }
}
eeq64g8w

eeq64g8w1#

首先你需要使connectDB异步,然后git摆脱mongoose.connection.once(),否则你需要所有的Mongoose代码都在那里。

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

async function main() {
  await connectDb('testDB');

  const catSchema = new mongoose.Schema({ name: String });
  const catDocument = mongoose.model('testColl', catSchema);

  const catObj = new catDocument({ name: 'Zildjian' });
  await catObj.save();
}

连接数据库

import mongoose from 'mongoose';
import { strict as assert } from 'assert';
import { readToml } from './readToml';

const db = readToml('./config/database.toml');

export async function connectDb(
  database: string = db.database,
  uri: string = db.uri,
  username: string = db.username,
  password: string = db.password,
) {
  assert(typeof uri === 'string');
  assert(typeof database === 'string');
  assert(typeof username === 'string');
  assert(typeof password === 'string');

  const URI = `mongodb+srv://${username}:${password}@${uri}/${database}?retryWrites=true&w=majority`;

  const options = {
    bufferCommands: false,
    autoCreate: false,
  };

  try {
    await mongoose.connect(URI, options);
  } catch (err: any) {
    throw err.message;
  }
}
cygmwpex

cygmwpex2#

请尝试以下代码并确保函数包含await关键字,该关键字应始终为async function(async关键字应在函数名之前使用)。但在您的情况下,回调函数已定义为async函数。
只需将保存部分单独更改为下面的内容,您就可以开始了。

try {
    const catModel = mongoose.model('testColl', catSchema);
    const cat = new catModel({ name: 'Zildjian' });
    const response = await cat.save(); // if error while saving, catch will get executed
    console.log(response); // saved record
    // return success response 
} catch (err) {
    console.log('err' + err);
    // return error response
}
rdrgkggo

rdrgkggo3#

为了使用await,你必须提供一个promise来等待。cat.save()返回一个promise,所以这应该可以工作。然而,你也只能在async函数中使用await,所以你也应该声明open事件的回调函数为async:

(async () => {
  connectDb('testDB');

  mongoose.connection.once('open', async () => {
    console.log('MongoDB is connected');

    mongoose.connection.db.listCollections().toArray(function (err, names) {
      console.log(names);
    });

    const catModel = mongoose.model('testColl', catSchema);

    const cat = new catModel({ name: 'Zildjian' });
    await cat.save();
    console.log('Saved in db');
  });
})();

相关问题