These are chat archives for Automattic/mongoose

21st
May 2018
Ehsan Shadmehri
@ehsansh
May 21 2018 10:13

hi, How is it possible to use asyns await inside a for loop which reads data from database? Please look at my codes:

async function findBuyId(buyIds,instrument) {
    for( const buyId of buyIds ){
        await Buy.findById({_id: buyId},function (err,buy) {
            if( buy.app == instrument ){
                return buy._id
            }
        })
    }
    return null
}

This function even when buy.app==instrument is true always returns null

Daniel Netzer
@DanielNetzer
May 21 2018 10:24
cause your return is outside await
Ehsan Shadmehri
@ehsansh
May 21 2018 10:57

@DanielNetzer Thanks. I removed the for loop and changed my code to this:

        let repeatBuyId = null
        await Buy.findOne({'_id':{$in: buyIds},app:instrument},function (err,buy) {
            repeatBuyId = buy._id
            console.log(repeatBuyId)
        })
        console.log(repeatBuyId)

It is strange that in console I see first null then the id. I expect the next lines after await should not be executed. Am I wrong?

Kev
@lineus
May 21 2018 10:58
@ehsansh you're passing a callback to findById and using a promise in the same call. It needs to be one or the other.
Ehsan Shadmehri
@ehsansh
May 21 2018 11:14
@lineus Thanks what is your idea about my second piece of code? It randomly shows an id and null in the console. what is the solution?
Kev
@lineus
May 21 2018 11:18

@ehsansh what I said applies to both of your examples:

await Buy.findOne({'_id':{$in: buyIds},app:instrument},function (err,buy) {
            repeatBuyId = buy._id
            console.log(repeatBuyId)
        })

you're passing a callback and awaiting a promise, this is problematic because each query will be run twice.

I would just use the promise example
in the first example, you can see that the findOne pre hook increments called 20 times instead of 10 ( once for each doc )
Ehsan Shadmehri
@ehsansh
May 21 2018 11:34
@lineus Thanks a lot. We should use promise or callback function not both of them. I did not know such an important case. I appreciate your help.
When we use only promises without callback function then next lines won't be executed until the promise has been done
How could we handle errors while using promises. Tray and catch ?
Kev
@lineus
May 21 2018 11:47
@ehsansh you can attach a catch method to the promise example
specifically line 40
Sedric Heidarizarei
@saeedhei
May 21 2018 11:51
@lineus please help me in my question, I have array of array with 2 same text field and 1 not same field, in secend level of child, How Should be my schema? Thanks.
Ehsan Shadmehri
@ehsansh
May 21 2018 11:52
@lineus Wow. It is much better than using try catch the code is much cleaner and easier to read. Thank you.
Kev
@lineus
May 21 2018 12:00
@saeedhei it's not entirely clear from your example why you're using a multi-dimensional array for inline_keyboard. I don't have any experience with 2d arrays and mongodb or mongoose but I'll give it a try. Can you elaborate on your need for the array of arrays?
@ehsansh you're welcome :)
Sedric Heidarizarei
@saeedhei
May 21 2018 12:19
@lineus That is for Telegram Bot, (https://core.telegram.org/bots/api#inlinekeyboardmarkup)
That object represents one button of an inline keyboard, With Different field, callback_data, url,or...
I need Something like this, not sure how to fix that
const childSchema = new Schema({
  reply_markup: {
    inline_keyboard: [
      [{
        text: String,
        callback_data: String,
      }],
      [{
        text: String,
        url: String,
      }],
  }
});
Kev
@lineus
May 21 2018 12:28
the extra info helps, thanks @saeedhei
I think you've uncovered a bug in mongoose, as I think that your example schema should work. will investigate further
Sedric Heidarizarei
@saeedhei
May 21 2018 12:33
Thank you Dear @lineus , I will Check that now 👍
Kev
@lineus
May 21 2018 13:31
I opened a bug #6493 @saeedhei . I'll take a look at it as soon as I can :)
Sedric Heidarizarei
@saeedhei
May 21 2018 14:12
@lineus appreciate it. 👍
James Gardner
@james-gardner
May 21 2018 14:54
Hey, if I want to format data in different ways before it gets saved should I use static methods, normal methods or middleware?
James Gardner
@james-gardner
May 21 2018 15:02
I've got two data sources with slightly different structures, I thought about having 'createFromWebhook' and 'createFromScraper' on the model.
But I'm also using findOneAndUpdate, so Ideally I would like to replace this
asmi77
@asmi77
May 21 2018 16:23
Hi everyone, I'm working on a MEVN app and struggling to store an image in mongoose DB, I converted this image into a BinaryData and a base64, if I try to store the base64, it tells me that the payload is too long, and if I try to to store the BinaryData, nothing happens, all the data are saved, except the image. I don't want to use GRIDfs or Multer, and would like to do it in Javascript, is it possible ?
image: { data: Buffer, contentType: String },
This is my schema type
Am I doing something wrong ?
Kev
@lineus
May 21 2018 18:39
@james-gardner did you sort something out?
Kev
@lineus
May 21 2018 18:55
@asmi77 can you provide an example that shows how you are creating and saving the doc? The schema path looks fine.
asmi77
@asmi77
May 21 2018 19:05
here is my express route creating a new product with an image
I have a doubt about the req.body.image, I'm not sure this is the right way to pass a binaryData
What do you think @lineus ?
I also have a doubt about the .save method, maybe it should be a push ?
Kev
@lineus
May 21 2018 19:11
@asmi77 when you add code blocks, put three tildes on the line directly above it and three tildes on the line directly below it to get code highlighting. Shift-Enter will let you add a new line without sending the message.
asmi77
@asmi77
May 21 2018 19:13
routerProducts.post("/send-product", [helpers.checkToken], (req, res) => {
  let user = res.locals.user;
  console.log("Found user: ", user);
  terminal.productsTerminal.note('req of post products', req)
  console.log('req: ', req)
  if (user === null) {
    res
      .status(401)
      .json({ success: false, message: "This user does not exist" });
  } else {
    console.log("lets create this product: ");
    let createdProduct = new Product(req.body);
    createdProduct.title = req.body.title;
    createdProduct.content = req.body.content;
    createdProduct.price = req.body.price;
    createdProduct.location = req.body.location;
    createdProduct.image = req.body.image;
    createdProduct.senderId = user.userID;
    createdProduct.createdDate = new Date();
    terminal.productsTerminal.note('req.body.image: ', req.body.image)
    terminal.productsTerminal.note("new product is : ", createdProduct.image.File);
    createdProduct.save((err, myNewProduct) => {
      terminal.productsTerminal.success("New Product: ", myNewProduct);
      if (err) {
        terminal.productsTerminal.warn("Your product has not been posted due to : ", err);
        res
          .status(500)
          .json({ success: false }, "Your product has not been posted");
      } else {
        console.log("Your new product has been posted: ", myNewProduct);
        res
          .status(200)
          .json({
            success: true,
            message: "Your product has been posted",
            myNewProduct: myNewProduct
          });
      }
    });
  }
});
Kev
@lineus
May 21 2018 19:13
much easier to read, thanks :)
asmi77
@asmi77
May 21 2018 19:14
Thank YOU :)
Kev
@lineus
May 21 2018 19:15
this line: createdProduct.image = req.body.image doesn't seem right unless req.body.image is already an object with data and contentType properties.
asmi77
@asmi77
May 21 2018 19:16
req.body.image is actually an object
But something is strange about this object
because it starts with file(909384039), and then starts the object
let me show you
image.png
This is what I get in my console
The image format is a file(with numbers) and then the object
And in the console of Vue.js(I don't know if you are familiar with Vue), when i log 'image', I just get "image: file"
I don't see the object with name, type , size properties, etc.
Kev
@lineus
May 21 2018 19:24
can you console.dir(req.body.image) and copy paste it into a gist and share the link here?
asmi77
@asmi77
May 21 2018 19:25
Oh, I don't know what is a gist
Kev
@lineus
May 21 2018 19:25
it's a github paste service
asmi77
@asmi77
May 21 2018 19:25
Ok
So it's console.dir, not console.log ?
Kev
@lineus
May 21 2018 19:26
you can create an anonymous gist or one associated with your user
yeah, dir will dig a little deeper.
asmi77
@asmi77
May 21 2018 19:26
Ok
perfect
One moment plz
asmi77
@asmi77
May 21 2018 19:34
The answer is so short that I don't need to paste it into a gist ....
'console dir :'
There is nothing, like it is empty
Kev
@lineus
May 21 2018 19:35
show me the line where you call console.dir
asmi77
@asmi77
May 21 2018 19:36
a printscreen would be better
image.png
Up is my line with console.dir
down is the console .dir content
Kev
@lineus
May 21 2018 19:37
you'll have to take out the 1st arg. console.dir doesn't do concatenation like .log.
it needs to be, console.dir(req.body.image)
asmi77
@asmi77
May 21 2018 19:37
Ah
ok
sorry
didn't know
Kev
@lineus
May 21 2018 19:37
no worries, I had to learn all this stuff too, and not all that long ago :smile:
process.stdout.write('console-dir:')
console.dir(req.body.image)
will have the effect you were going for originally.
process.stdout.write doesn't add \n
asmi77
@asmi77
May 21 2018 19:39
I only get an empty {}
Kev
@lineus
May 21 2018 19:40
what's the name of the field in the upload form? fiy, you can also do console.dir(req.body) to see the properties there.
asmi77
@asmi77
May 21 2018 19:41
and with process.stdout.write etc. this is what I get : console-dir:{}
Kev
@lineus
May 21 2018 19:42
is your code checked into github @asmi77 ?
asmi77
@asmi77
May 21 2018 19:43
No, this is another one, but I can push it so you can test if you want
Kev
@lineus
May 21 2018 19:43
if you like, I'm happy to take a look
asmi77
@asmi77
May 21 2018 19:43
That's so nice
asmi77
@asmi77
May 21 2018 19:49
Don't take into account the README file, it is not up-to-date
asmi77
@asmi77
May 21 2018 20:26
Ok, I think that I see what is the problem, I think that I'm trying to pass a file with the body, and bodyParser can't parse it because my image is a file !
Kev
@lineus
May 21 2018 20:29
that makes sense, it took me a while to get the app up and running :)
this page has some suggestions
asmi77
@asmi77
May 21 2018 20:36
Thank you, I'm working on it right now. I do not sleep until I have fixed the problem.
I'll let you know
Thank you so much for your time, and help, I really appreciate.