Home > Software engineering >  Generating query objects for mongoose query
Generating query objects for mongoose query

Time:09-21

        const query = {}
        query['title'] = 'bogustest' //item.title
        const storedProduct = await this.ProductModel
            .findOneAndUpdate({ id: item.id }, {$set:{"title": "bogustest"}}, { upsert: true, new: true })
            .lean<MongoDB.IProductDocument>()
            .exec()

This works, but when I change it to:

        const query = {}
        query['title'] = 'bogustest' //item.title
        const storedProduct = await this.ProductModel
            .findOneAndUpdate({ id: item.id }, {$set:{query}}, { upsert: true, new: true })
            .lean<MongoDB.IProductDocument>()
            .exec()

It doesn't work. Is there a way to change it so that title is between quotes? I want to change 'title' to a variable called field and make it more generic, not sure why it's not working. I think I found a post on stackoverflow saying it would work, but console logging query gives me {title: 'bogustest'} instead of {'title': 'bogustest'}

CodePudding user response:

You need {...query}.

{query} is the shorthand for {query: query}

  • Related