Updating using $inc field in the mongo gives me this error

So I’m trying to update a fied 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 command I get some error. I’ve made sure that the given _id exisits 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

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:914:22)

THanks. Here is how I’m doing my caller function.
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
            ) {
              

Hello!

There seems to be a problem with the caller, not the code that you provided. Can you show us the code that calls getNextSequence?

1 Like

THanks. Here is how I’m doing my caller function.
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);
        });

      
    }
});

I can’t believe this line works :laughing:!

return console.log("error in url" + err);

I can’t find anything saying that it should return the resulting string… seems weird… never mind. Now, to the issue…

The problem is that you’re not awaiting the result from getNextSequence and you’re not declaring the surrounding function as async. Declaring a function as async makes that function return an implicit Promise, meaning that the caller still needs to handle it as that:

async function promised() {
  const someValue = await someResult();
  return someValue;
}

// This is how you would "use" it
promised()
.then()
.catch()
.finally();

In your case, the UrlMode.find callback should be async. By the way, the getNextSequence should be called only once, otherwise the value would increase without actually adding a new record, no?

Edit

In addition to my response:

1 Like

I completed by replacing everything with thenables. Thanks anyhow. :slight_smile:

1 Like