using async/await in mongoose schema subdocument [duplicate]












1
















This question already has an answer here:




  • why mongoose queries dos not work when put inside promise function

    1 answer




I have been trying to get an ID from TransactionType Schema and use it as a reference in the new Category but it always calls to create the new category before it finishes the query of new TransactionType.



const Category = require("../models/categories.model");
const TransactionType = require("../models/transactiontype.model");
async function saveNewCategory(req, res, next) {
let transactionID;
const transID = await TransactionType.findOne({ name: req.body.transactionType })
.populate("transactionType")
.exec((error, res) => {
console.log(res.id);
transactionID = res.id;
console.log(transactionID);
return transactionID;
});

const newCategory = await new Category({
name: req.body.name,
transactionType: transactionID || transID ,
image: req.body.image,
description: req.body.description
});
try {
await newCategory.save();
await res
.status(200)
.send({ response: "Response " + JSON.stringify(req.body, undefined, 2) });
} catch (error) {
console.log(error);
}
};
module.exports = {
saveNewCategory
};


It creates newCategory with transactionType undefined before it finishes transID.
Please find below the Schema for Category.



const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const category = new Schema({
name: String,
transactionType : {
type: Schema.Types.ObjectId,
ref: "TransactionType"
},
image: String,
description: String
});

const Category = mongoose.model('Category', category);
module.exports = Category;


Find below the TransactionType model



const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const transactionType = new Schema({
transaction: String
});
const TransactionType = mongoose.model('TransactionType', transactionType);
module.exports = TransactionType;


I will be grateful if anyone could assist me with understanding this. I have gone through many books and blogs to understand async await but still no answer.










share|improve this question













marked as duplicate by Neil Lunn javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 23 '18 at 8:06


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.



















  • const transID = await TransactionType.findOne({ name: req.body.transactionType }) .populate("transactionType") That's already a promise and you don't need the exec() and callback. Also really would be best to be inside the try. And the new Category() is not actually async, so you don't need to await it. Make the change to the first method, remove the await on the new Category() and then move all that code inside the try block at the top of it. Job done.

    – Neil Lunn
    Nov 23 '18 at 8:01











  • Wow.. It hit the nail right on the head... Thank you @NeilLunn... Perfect job...

    – Andrew Ogaga
    Nov 23 '18 at 8:38


















1
















This question already has an answer here:




  • why mongoose queries dos not work when put inside promise function

    1 answer




I have been trying to get an ID from TransactionType Schema and use it as a reference in the new Category but it always calls to create the new category before it finishes the query of new TransactionType.



const Category = require("../models/categories.model");
const TransactionType = require("../models/transactiontype.model");
async function saveNewCategory(req, res, next) {
let transactionID;
const transID = await TransactionType.findOne({ name: req.body.transactionType })
.populate("transactionType")
.exec((error, res) => {
console.log(res.id);
transactionID = res.id;
console.log(transactionID);
return transactionID;
});

const newCategory = await new Category({
name: req.body.name,
transactionType: transactionID || transID ,
image: req.body.image,
description: req.body.description
});
try {
await newCategory.save();
await res
.status(200)
.send({ response: "Response " + JSON.stringify(req.body, undefined, 2) });
} catch (error) {
console.log(error);
}
};
module.exports = {
saveNewCategory
};


It creates newCategory with transactionType undefined before it finishes transID.
Please find below the Schema for Category.



const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const category = new Schema({
name: String,
transactionType : {
type: Schema.Types.ObjectId,
ref: "TransactionType"
},
image: String,
description: String
});

const Category = mongoose.model('Category', category);
module.exports = Category;


Find below the TransactionType model



const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const transactionType = new Schema({
transaction: String
});
const TransactionType = mongoose.model('TransactionType', transactionType);
module.exports = TransactionType;


I will be grateful if anyone could assist me with understanding this. I have gone through many books and blogs to understand async await but still no answer.










share|improve this question













marked as duplicate by Neil Lunn javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 23 '18 at 8:06


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.



















  • const transID = await TransactionType.findOne({ name: req.body.transactionType }) .populate("transactionType") That's already a promise and you don't need the exec() and callback. Also really would be best to be inside the try. And the new Category() is not actually async, so you don't need to await it. Make the change to the first method, remove the await on the new Category() and then move all that code inside the try block at the top of it. Job done.

    – Neil Lunn
    Nov 23 '18 at 8:01











  • Wow.. It hit the nail right on the head... Thank you @NeilLunn... Perfect job...

    – Andrew Ogaga
    Nov 23 '18 at 8:38
















1












1








1









This question already has an answer here:




  • why mongoose queries dos not work when put inside promise function

    1 answer




I have been trying to get an ID from TransactionType Schema and use it as a reference in the new Category but it always calls to create the new category before it finishes the query of new TransactionType.



const Category = require("../models/categories.model");
const TransactionType = require("../models/transactiontype.model");
async function saveNewCategory(req, res, next) {
let transactionID;
const transID = await TransactionType.findOne({ name: req.body.transactionType })
.populate("transactionType")
.exec((error, res) => {
console.log(res.id);
transactionID = res.id;
console.log(transactionID);
return transactionID;
});

const newCategory = await new Category({
name: req.body.name,
transactionType: transactionID || transID ,
image: req.body.image,
description: req.body.description
});
try {
await newCategory.save();
await res
.status(200)
.send({ response: "Response " + JSON.stringify(req.body, undefined, 2) });
} catch (error) {
console.log(error);
}
};
module.exports = {
saveNewCategory
};


It creates newCategory with transactionType undefined before it finishes transID.
Please find below the Schema for Category.



const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const category = new Schema({
name: String,
transactionType : {
type: Schema.Types.ObjectId,
ref: "TransactionType"
},
image: String,
description: String
});

const Category = mongoose.model('Category', category);
module.exports = Category;


Find below the TransactionType model



const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const transactionType = new Schema({
transaction: String
});
const TransactionType = mongoose.model('TransactionType', transactionType);
module.exports = TransactionType;


I will be grateful if anyone could assist me with understanding this. I have gone through many books and blogs to understand async await but still no answer.










share|improve this question















This question already has an answer here:




  • why mongoose queries dos not work when put inside promise function

    1 answer




I have been trying to get an ID from TransactionType Schema and use it as a reference in the new Category but it always calls to create the new category before it finishes the query of new TransactionType.



const Category = require("../models/categories.model");
const TransactionType = require("../models/transactiontype.model");
async function saveNewCategory(req, res, next) {
let transactionID;
const transID = await TransactionType.findOne({ name: req.body.transactionType })
.populate("transactionType")
.exec((error, res) => {
console.log(res.id);
transactionID = res.id;
console.log(transactionID);
return transactionID;
});

const newCategory = await new Category({
name: req.body.name,
transactionType: transactionID || transID ,
image: req.body.image,
description: req.body.description
});
try {
await newCategory.save();
await res
.status(200)
.send({ response: "Response " + JSON.stringify(req.body, undefined, 2) });
} catch (error) {
console.log(error);
}
};
module.exports = {
saveNewCategory
};


It creates newCategory with transactionType undefined before it finishes transID.
Please find below the Schema for Category.



const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const category = new Schema({
name: String,
transactionType : {
type: Schema.Types.ObjectId,
ref: "TransactionType"
},
image: String,
description: String
});

const Category = mongoose.model('Category', category);
module.exports = Category;


Find below the TransactionType model



const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const transactionType = new Schema({
transaction: String
});
const TransactionType = mongoose.model('TransactionType', transactionType);
module.exports = TransactionType;


I will be grateful if anyone could assist me with understanding this. I have gone through many books and blogs to understand async await but still no answer.





This question already has an answer here:




  • why mongoose queries dos not work when put inside promise function

    1 answer








javascript node.js mongoose schema






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 23 '18 at 7:40









Andrew OgagaAndrew Ogaga

62




62




marked as duplicate by Neil Lunn javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 23 '18 at 8:06


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by Neil Lunn javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 23 '18 at 8:06


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.















  • const transID = await TransactionType.findOne({ name: req.body.transactionType }) .populate("transactionType") That's already a promise and you don't need the exec() and callback. Also really would be best to be inside the try. And the new Category() is not actually async, so you don't need to await it. Make the change to the first method, remove the await on the new Category() and then move all that code inside the try block at the top of it. Job done.

    – Neil Lunn
    Nov 23 '18 at 8:01











  • Wow.. It hit the nail right on the head... Thank you @NeilLunn... Perfect job...

    – Andrew Ogaga
    Nov 23 '18 at 8:38





















  • const transID = await TransactionType.findOne({ name: req.body.transactionType }) .populate("transactionType") That's already a promise and you don't need the exec() and callback. Also really would be best to be inside the try. And the new Category() is not actually async, so you don't need to await it. Make the change to the first method, remove the await on the new Category() and then move all that code inside the try block at the top of it. Job done.

    – Neil Lunn
    Nov 23 '18 at 8:01











  • Wow.. It hit the nail right on the head... Thank you @NeilLunn... Perfect job...

    – Andrew Ogaga
    Nov 23 '18 at 8:38



















const transID = await TransactionType.findOne({ name: req.body.transactionType }) .populate("transactionType") That's already a promise and you don't need the exec() and callback. Also really would be best to be inside the try. And the new Category() is not actually async, so you don't need to await it. Make the change to the first method, remove the await on the new Category() and then move all that code inside the try block at the top of it. Job done.

– Neil Lunn
Nov 23 '18 at 8:01





const transID = await TransactionType.findOne({ name: req.body.transactionType }) .populate("transactionType") That's already a promise and you don't need the exec() and callback. Also really would be best to be inside the try. And the new Category() is not actually async, so you don't need to await it. Make the change to the first method, remove the await on the new Category() and then move all that code inside the try block at the top of it. Job done.

– Neil Lunn
Nov 23 '18 at 8:01













Wow.. It hit the nail right on the head... Thank you @NeilLunn... Perfect job...

– Andrew Ogaga
Nov 23 '18 at 8:38







Wow.. It hit the nail right on the head... Thank you @NeilLunn... Perfect job...

– Andrew Ogaga
Nov 23 '18 at 8:38














1 Answer
1






active

oldest

votes


















0














I think you can put everything whats async in an immediate async function. This way the saveNewCategory won`t end before your async opereations finish.



async function saveNewCategory(req, res, next) {
(async () => {
await asyncStuff()
})()
}


Edit: to understand better async await and promises check this article out:
https://pouchdb.com/2015/03/05/taming-the-async-beast-with-es7.html






share|improve this answer






























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    I think you can put everything whats async in an immediate async function. This way the saveNewCategory won`t end before your async opereations finish.



    async function saveNewCategory(req, res, next) {
    (async () => {
    await asyncStuff()
    })()
    }


    Edit: to understand better async await and promises check this article out:
    https://pouchdb.com/2015/03/05/taming-the-async-beast-with-es7.html






    share|improve this answer




























      0














      I think you can put everything whats async in an immediate async function. This way the saveNewCategory won`t end before your async opereations finish.



      async function saveNewCategory(req, res, next) {
      (async () => {
      await asyncStuff()
      })()
      }


      Edit: to understand better async await and promises check this article out:
      https://pouchdb.com/2015/03/05/taming-the-async-beast-with-es7.html






      share|improve this answer


























        0












        0








        0







        I think you can put everything whats async in an immediate async function. This way the saveNewCategory won`t end before your async opereations finish.



        async function saveNewCategory(req, res, next) {
        (async () => {
        await asyncStuff()
        })()
        }


        Edit: to understand better async await and promises check this article out:
        https://pouchdb.com/2015/03/05/taming-the-async-beast-with-es7.html






        share|improve this answer













        I think you can put everything whats async in an immediate async function. This way the saveNewCategory won`t end before your async opereations finish.



        async function saveNewCategory(req, res, next) {
        (async () => {
        await asyncStuff()
        })()
        }


        Edit: to understand better async await and promises check this article out:
        https://pouchdb.com/2015/03/05/taming-the-async-beast-with-es7.html







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 23 '18 at 7:44









        Bogdan M.Bogdan M.

        1,25052247




        1,25052247

















            Popular posts from this blog

            "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

            Alcedinidae

            RAC Tourist Trophy