Ashutosh Soni
Ashutosh Soni

Reputation: 1015

Updating using $inc field in the mongo gives error

So I’m trying to update a field in my DB to increase it every time. like a counter so that I keep getting the updated values. for that, I’m using this

var CounterSchema = new Schema({
  _id: String,
  _const: String,
  count: Number
});

then I created my model as

const Counter = mongoose.model("counter", CounterSchema);

then I am using a function to update a field in my collection such as the following…

async function getNextSequence() {
 

  var count = await Counter.findOneAndUpdate(
    { _const: "some" },

    { $inc: { count: 1 } },
    { new: true }
  );

  
  return count.count;
}

But on running the above functions get some error. I’ve made sure that the given _id exists and this is the error I get…

(node:10788) DeprecationWarning: Mongoose: `findOneAndUpdate()` and `findOneAndDelete()` without the `useFindAndModify` option set to false are deprecated. See: https://mongoosejs.com/docs/deprecations.html#findandmodify

9:58 PM

{ ValidationError: Url validation failed: counter: Cast to Number failed for value "Promise { <pending> }" at path "counter"

9:58 PM

at ValidationError.inspect (/rbd/pnpm-volume/f971d4d8-b5ba-4fbb-87f2-7580f1e7da53/node_modules/.registry.npmjs.org/mongoose/5.9.7/node_modules/mongoose/lib/error/validation.js:61:24)

9:58 PM

at formatValue (internal/util/inspect.js:493:31)

9:58 PM

at inspect (internal/util/inspect.js:191:10)

9:58 PM

at Object.formatWithOptions (util.js:84:12)

9:58 PM

at Console.(anonymous function) (console.js:191:15)

9:58 PM

at Console.log (console.js:202:31)

9:58 PM

Jump Toat /app/server.js:107:39

9:58 PM

at /rbd/pnpm-volume/f971d4d8-b5ba-4fbb-87f2-7580f1e7da53/node_modules/.registry.npmjs.org/mongoose/5.9.7/node_modules/mongoose/lib/helpers/promiseOrCallback.js:16:11

9:58 PM

at /rbd/pnpm-volume/f971d4d8-b5ba-4fbb-87f2-7580f1e7da53/node_modules/.registry.npmjs.org/mongoose/5.9.7/node_modules/mongoose/lib/model.js:4860:21

9:58 PM

at _done (/rbd/pnpm-volume/f971d4d8-b5ba-4fbb-87f2-7580f1e7da53/node_modules/.registry.npmjs.org/mongoose/5.9.7/node_modules/mongoose/lib/model.js:3120:16)

9:58 PM

at fn (/rbd/pnpm-volume/f971d4d8-b5ba-4fbb-87f2-7580f1e7da53/node_modules/.registry.npmjs.org/mongoose/5.9.7/node_modules/mongoose/lib/model.js:3135:18)

9:58 PM

at callbackWrapper (/rbd/pnpm-volume/f971d4d8-b5ba-4fbb-87f2-7580f1e7da53/node_modules/.registry.npmjs.org/mongoose/5.9.7/node_modules/mongoose/lib/model.js:3089:20)

9:58 PM

at /rbd/pnpm-volume/f971d4d8-b5ba-4fbb-87f2-7580f1e7da53/node_modules/.registry.npmjs.org/mongoose/5.9.7/node_modules/mongoose/lib/model.js:4837:16

9:58 PM

at /rbd/pnpm-volume/f971d4d8-b5ba-4fbb-87f2-7580f1e7da53/node_modules/.registry.npmjs.org/mongoose/5.9.7/node_modules/mongoose/lib/helpers/promiseOrCallback.js:16:11

9:58 PM

at /rbd/pnpm-volume/f971d4d8-b5ba-4fbb-87f2-7580f1e7da53/node_modules/.registry.npmjs.org/mongoose/5.9.7/node_modules/mongoose/lib/model.js:4860:21

9:58 PM

at $__save.error (/rbd/pnpm-volume/f971d4d8-b5ba-4fbb-87f2-7580f1e7da53/node_modules/.registry.npmjs.org/mongoose/5.9.7/node_modules/mongoose/lib/model.js:489:16)

9:58 PM

errors:

9:58 PM

{ counter:

9:58 PM

{ CastError: Cast to Number failed for value "Promise { <pending> }" at path "counter"

9:58 PM

at new CastError (/rbd/pnpm-volume/f971d4d8-b5ba-4fbb-87f2-7580f1e7da53/node_modules/.registry.npmjs.org/mongoose/5.9.7/node_modules/mongoose/lib/error/cast.js:29:11)

9:58 PM

at model.$set (/rbd/pnpm-volume/f971d4d8-b5ba-4fbb-87f2-7580f1e7da53/node_modules/.registry.npmjs.org/mongoose/5.9.7/node_modules/mongoose/lib/document.js:1233:9)

9:58 PM

at model._handleIndex (/rbd/pnpm-volume/f971d4d8-b5ba-4fbb-87f2-7580f1e7da53/node_modules/.registry.npmjs.org/mongoose/5.9.7/node_modules/mongoose/lib/document.js:972:14)

9:58 PM

I have a post api to update the counter. I have made two schema one to keep track of updates and other to push the real updated count… anyhow I was jus trying new stuff.!!

app.post("/api/shorturl/new", function(req, res) {
  var url = req.body.url;
  url = url.replace(/^https?:\/\//, "");
  console.log("url string" + url);

  dns.lookup(url, async function(err, address, family) {
    if (err) {
      return console.log("error in url" + err);
    } else {
      console.log("inside else lookup");

      UrlModel.find({ url: url })
        .then(hello => {
          if (hello.length == 0) {
            console.log("url length is 0");
            console.log("url length is 0" + getNextSequence());

            UrlModel.create({ url: url, counter: getNextSequence() }, function(
              err,
              url
            ) {
              if (err) return console.log(err);
              else return res.json({ success: url });
            });
          } else {
            console.log("not 0");
            //           return the index of the sored file
          }
        })
        .catch(message => {
          console.log("error message catch" + message);
        });

      
    }
});

Upvotes: 1

Views: 152

Answers (2)

Yilmaz
Yilmaz

Reputation: 49182

the return value for the function that you wrote is a promise because after await

return line is executed and it returns a promise. In order to get this promise resolved you also have to wrap this function with an async function.

async function run() {
  const sequence = await getNextSequence();
  console.log(sequence);
}

run();

now you will get what you intended.

Upvotes: 1

Plancke
Plancke

Reputation: 1139

You've defined getNextSequence as an async function so it'll automatically wrap it into a Promise. Try changing it to:

UrlModel.create({ url: url, counter: await getNextSequence() }, ...

Upvotes: 0

Related Questions