Reputation: 1767
I know this sounds rediculess...
In my function index()
I retrieve a Model for a specific collectionName
promted by commandline parameters. After a async AXIOS API call a saveToDB(response, model)
is called.
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")
})
}
So basicly this should easily work, but the strange thing is. This does only! work, if I save another document prior to calling saveToDB()
in index()
. Changing the function to;
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 => {
...
})
})
}
Is there anything strange going on I am not aware of? Excuse my super unspecific question.
Upvotes: 0
Views: 106
Reputation: 4452
Why are you consuming and "awaiting" the Promises
at the same time. Why don't you keep it simple like this:
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);
}
}
Upvotes: 0
Reputation: 11
Maybe you should read the docu: https://mongoosejs.com/ or search for related questions. I guess its not a mongoos problem.
Upvotes: 1