简体   繁体   中英

node mongoose how to auto increment

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**

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`
      });

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM