Mongoose Object.save() 仅在调用两次时才有效

时间:2021-03-28 12:26:02

标签: javascript node.js mongodb mongoose

我知道这听起来很可笑... 在我的函数 index() 中,我检索了命令行参数提示的特定 collectionName 的模型。在异步 AXIOS API 调用之后,会调用 saveToDB(response, model)

export async function index(collectionName) {
  let model = getModelForCollection(collectionName)

  await axios.get(url)
            .then(resp => {
                saveToDB(resp.data, model)
                    .then(saved => {
                        ...
                    })
            })
}

async function saveToDB(response, model) {
    
  const word = new model({response})
  await word.save()
     .then(() => {
         console.log("saved")
     })
}

所以基本上这应该很容易工作,但奇怪的是。这只做!工作,如果我在 saveToDB() 中调用 index() 之前保存另一个文档。将函数更改为;

export async function index(collectionName) {
  let model = getModelForCollection(collectionName)

  let word = new model({word: 'WORT'})
  await word.save().then(() => {
      console.log("saved")
  })

  await axios.get(url)
            .then(resp => {
                saveToDB(resp.data, model)
                    .then(saved => {
                        ...
                    })
            })
}

有什么我不知道的奇怪事情吗?原谅我超级不具体的问题。

2 个答案:

答案 0 :(得分:1)

也许你应该阅读文档:https://mongoosejs.com/ 或搜索相关问题。我想这不是猫鼬问题。

答案 1 :(得分:0)

你为什么同时消费和“等待”Promises。你为什么不像这样保持简单:

export async function index(collectionName) {
  try {
    let model = getModelForCollection(collectionName)

    let resp = await axios.get(url);
    let saved = await saveToDB(resp.data, model);
  } catch (error) {
    console.log("Error");
    console.log(error);
  }
}

async function saveToDB(response, model) {
  try {
    const word = new model({ response });

    let writeStatus = await word.save();
    console.log("saved");
  } catch (error) {
    console.log("Error");
    console.log(error);
  }   
}
相关问题