Home > Blockchain >  node mongoose how to auto increment
node mongoose how to auto increment

Time:06-25

Trying to follow the example here: https://www.tutorialspoint.com/mongodb/mongodb_autoincrement_sequence.htm

export interface RowProps {
  id?: number; // This is to auto increment
  todoText: string;
}
const addAutoIncrement = async ({ db, collectionName, todoText }) => {
  const getNextSequenceValue = (sequenceName: string) => {
    const sequenceDocument = db
      .collection<RowProps>(collectionName)
      .findAndModify({
        query: { _id: sequenceName },
        update: { $inc: { sequence_value: 1 } },
        new: true,
      });
    console.log('sequenceD', sequenceDocument)
    return sequenceDocument.sequence_value;
  };


  db.collection<RowPropsClient>(collectionName).insertOne(
    {
      id: getNextSequenceValue('id'),
      todoText
    },
    (err) => {
      if (err) {
        console.log("err");
      }
    }
  );
}
// db is already defined and works
// I can add to the collection so this also works.
 addAutoIncrement({ db, collectionName: 'todos', todoText: 'hello' });

Error: throw new Error('Collection#findAndModify unimplemented by driver'); ^ Error: Collection#findAndModify unimplemented by driver

update

Tried to follow this example:

const addAutoIncrement = async ({ db, collectionName, todoText }) => {
  const modelTodo =  db.model(collectionName, TodosSchema);
  const res = await new modelTodo({ todoText }).save();
  const { _id } = res;

  return new Promise((resolve, reject) => {
    modelTodo.findOneAndUpdate(
      { _id },
      { $inc: { id: 1 } },
      { new: true },
      (err, res) => {
        if (err) {
          reject(err);
        }
        resolve(res);
      }
    );
  });
};

**The result is just setting the value to 1 each time - not incrementing**

CodePudding user response:

Collection#findAndModify() is a method that is implemented in the MongoDB shell, but not in the Node.js driver.

You should use Collection#findOneAndUpdate instead:

const { value : sequenceDocument } = db
      .collection<RowProps>(collectionName)
      .findOneAndUpdate({
        { _id: sequenceName },
        { $inc: { sequence_value: 1 } },
        { returnDocument : 'after' }   // equivalent to `new: true`
      });

CodePudding user response:

ok I don't know why I didnt do this before. All the online examples make everything unnecessarily complicated.

Just get the total count and then add it.

const addAndIncrement = async ({ db, collection, todoText }) => {
  const connectedModel =  db.model(collection, TodosSchema);
  const documentCount = await connectedModel.count({}); // get the total count
  return new connectedModel({ todoText, id: documentCount }).save();
};

Unless anyone comes up with a more performant way, this is what I'm going with.

  • Related