Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

version key missing when using bulkWrite insertOne method #13944

Closed
2 tasks done
Amarsingh1303 opened this issue Oct 6, 2023 · 3 comments · Fixed by #13981
Closed
2 tasks done

version key missing when using bulkWrite insertOne method #13944

Amarsingh1303 opened this issue Oct 6, 2023 · 3 comments · Fixed by #13981
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.
Milestone

Comments

@Amarsingh1303
Copy link

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

7.5.3

Node.js version

18.16.0

MongoDB server version

7.0.2

Typescript version (if applicable)

No response

Description

when using bulkWrite insertOne method version key is missing.
image

Steps to Reproduce

Hit POST api/user with body params and the version key is there with __v

{
    "fname":"abc",
    "lname":"dce",
    "city":"city1"
}

Hit PATCH api/user/bulkWrite with body params

[
    {
         "fname": "abc updated",
        "lname": "dce updated",
        "city": "city1 updated",
        "_id": "65204dcc93f235383b47695d"
    },
    {
        "fname": "dce",
        "lname": "ggg",
        "city": "ccc"
    }
]

First document will be updated but in the newly created document version key is missing.

POST API Description

app.post("/api/user", (req, res, next) => {
  const temp = new User(req.body);
  temp
    .save()
    .then(() => {
      res.json({ savedDocument: temp });
      next();
    })
    .catch((e) => {
      console.log("error", e);
      next();
    });
});

PATCH API description

app.patch("/api/user/bulkwrite", (req, res, next) => {
  const data = req.body;
  const commandData = data.map((item) => {
    if (item._id) {
      return {
        updateOne: {
          filter: { _id: item._id },
          update: item,
        },
      };
    } else {
      return {
        insertOne: {
          document: item,
        },
      };
    }
  });
  User.bulkWrite(commandData, { ordered: false })
    .then((res) => {
      console.log(res);
    })
    .catch((err) => console.log(err))
    .finally(() => {
      res.json({ ok: "ok" });
      next();
    });
});

Expected Behavior

version key should be available in the newly created document using bulkWrite insertOne method

@IslandRhythms IslandRhythms added the needs repro script Maybe a bug, but no repro script. The issue reporter should create a script that demos the issue label Oct 6, 2023
@Amarsingh1303
Copy link
Author

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const PORT = 5000;

const Schema = mongoose.Schema;
const userSchema = new Schema({
  fname: { type: String, required: true },
  lname: { type: String },
  city: { type: String },
});
const User = mongoose.model("User", userSchema);

app.use(bodyParser.json());

app.get("/user", (req, res, next) => {
  User.find()
    .then((result) => res.json({ data: result }))
    .catch((e) => console.log(e))
    .finally(() => next());
});

app.post("/api/user", (req, res, next) => {
  const temp = new User(req.body);
  temp
    .save()
    .then(() => {
      res.json({ savedDocument: temp });
      next();
    })
    .catch((e) => {
      console.log("error", e);
      next();
    });
});

app.patch("/api/user/bulkwrite", (req, res, next) => {
  const data = req.body;
  const commandData = data.map((item) => {
    if (item._id) {
      return {
        updateOne: {
          filter: { _id: item._id },
          update: item,
        },
      };
    } else {
      return {
        insertOne: {
          document: item,
        },
      };
    }
  });
  User.bulkWrite(commandData, { ordered: false })
    .then((res) => {
      console.log(res);
    })
    .catch((err) => console.log(err))
    .finally(() => {
      res.json({ ok: "ok" });
      next();
    });
});

mongoose
  .connect("mongodb://127.0.0.1:27017/check-verfydb")
  .then(() => {
    app.listen(process.env.PORT || PORT, () => {
      console.log(`server running on port ${PORT} `);
    });
  })
  .catch((e) => {
    console.log("Error Occured while starting server", e);
  });

@vkarpov15 vkarpov15 added has repro script There is a repro script, the Mongoose devs need to confirm that it reproduces the issue and removed needs repro script Maybe a bug, but no repro script. The issue reporter should create a script that demos the issue labels Oct 8, 2023
@vkarpov15 vkarpov15 added this to the 7.6.2 milestone Oct 8, 2023
@IslandRhythms IslandRhythms added can't reproduce Mongoose devs have been unable to reproduce this issue. Close after 14 days of inactivity. and removed has repro script There is a repro script, the Mongoose devs need to confirm that it reproduces the issue labels Oct 10, 2023
@IslandRhythms
Copy link
Collaborator

Please modify the script below to demonstrate your issue.

const mongoose = require('mongoose');

const { Schema } = mongoose;

const userSchema = new Schema({
  fname: { type: String, required: true },
  lname: { type: String },
  city: { type: String },
});
const User = mongoose.model("User", userSchema);

async function run() {
  await mongoose.connect('mongodb://localhost:27017');
  await mongoose.connection.dropDatabase();

  await User.create({
    fname: 'test',
    lname: 'testerson',
    city: 'exam'
  });
  await User.create({
    fname: 'John',
    lname: 'Jacob',
    city: 'Jingleheimerschmitz'
  });
  const data = await User.find();

  const commandData = await data.map((item) => {
    if (item._id) {
      return { updateOne: {
          filter: { _id: item._id },
          update: item
        }
      }
    } else {
      return {
        insertOne: {
          document: item
        }
      }
    }
  });

  console.log('what is command data', commandData);

  await User.bulkWrite(commandData, { ordered: false });

  const test = await User.find();

  console.log('test', test);

}

run();

@Amarsingh1303
Copy link
Author

Amarsingh1303 commented Oct 10, 2023

Hi @IslandRhythms Can you please take a look at the updated script.

const mongoose = require("mongoose");

const { Schema } = mongoose;

const userSchema = new Schema({
  fname: { type: String, required: true },
  lname: { type: String },
  city: { type: String },
});
const User = mongoose.model("User", userSchema);

async function run() {
  await mongoose.connect("mongodb://127.0.0.1:27017/dbName");
  await mongoose.connection.dropDatabase();

  await User.create({
    fname: "test",
    lname: "testerson",
    city: "exam",
  });
  const data = await User.find();
  const oneDataUpdateOneDataInsert = [
    ...data,
    {
      fname: "John",
      lname: "Jacob",
      city: "Jingleheimerschmitz",
    },
  ];

  const dataToUpdateAndInsert = await oneDataUpdateOneDataInsert.map((item) => {
    if (item._id) {
      return {
        updateOne: {
          filter: { _id: item._id },
          update: item,
        },
      };
    } else {
      return {
        insertOne: {
          document: item,
        },
      };
    }
  });

  console.log("dataToUpdateAndInsert", dataToUpdateAndInsert);

  await User.bulkWrite(dataToUpdateAndInsert, { ordered: false });

  const test = await User.find();

  console.log("test", test);
}

run();

image
image

@IslandRhythms IslandRhythms added has repro script There is a repro script, the Mongoose devs need to confirm that it reproduces the issue confirmed-bug We've confirmed this is a bug in Mongoose and will fix it. and removed can't reproduce Mongoose devs have been unable to reproduce this issue. Close after 14 days of inactivity. has repro script There is a repro script, the Mongoose devs need to confirm that it reproduces the issue labels Oct 11, 2023
@vkarpov15 vkarpov15 modified the milestones: 7.6.4, 7.6.3 Oct 13, 2023
vkarpov15 added a commit that referenced this issue Oct 17, 2023
fix(model): add versionKey to bulkWrite when inserting or upserting
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants