0

I'm using mongo db with mongoose and node.js making a web app. I want to update the "stocks" value of all entries of the mongo db using a function. The mongo methods allow you to do specific functions, such as multiplying or adding, but I want a unique function. For example, Topic is the mongoose object, and a common mongo method looks like:

Topic.update(
   { _id: 1 },
   { $inc: { stock: 5 },
   { multi: true }
)

This says to update all entries with _id: 1 by adding 5 to every "stock". What if I want to use a function like (stock * a)+b, where a is a variable defined before the Topic.update method and b is another category in the Topic mongo db.

One way might be to use Topic.find({}) and save to an array, then iterate through it with javascript array methods, then save this as the mongo Topic. But isn't there a way to do this with mongo simpler? A built in method?

A broader question is what are stardard mongoose/mongo/javascript practices and workflow for updating dbs, and more importantly, where do I find them!

bobbyb
  • 1

1 Answers1

1

The mongo methods allow you to do specific functions, such as multiplying or adding, but I want a unique function.

Nope, if you want to be fast, you're limited to the built-in operators. No custom functions for you. And no referencing other fields/documents.

(which is a pity, really. The need to reference other fields in the document is so natural, one would think...)

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367