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

findOneAndUpdate with upsert & setDefaultsOnInsert options returns MongoServerError on nested object properties update #12279

Closed
2 tasks done
AProts opened this issue Aug 15, 2022 · 2 comments · Fixed by #12390
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.
Milestone

Comments

@AProts
Copy link

AProts commented Aug 15, 2022

Prerequisites

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

Mongoose version

6.5.2

Node.js version

14.20.0

MongoDB server version

4.4.15

Description

MongoServerError: Updating the path 'x.y' would create a conflict at 'x' received after an attempt to update nested object properties using findOneAndUpdate with upsert & setDefaultsOnInsert options.

Steps to Reproduce

Model and Query:

await run().catch((err) => console.log(err));

async function run() {
  await mongoose.connect("url");

  const SUBSCRIPTIONS_CONFIG_DEFAULT = {
    hasPaidSubscription: false,
    hasPastDueInvoice: false,
  };

  const SubscriptionsConfigSchema = new mongoose.Schema(
    {
      hasPaidSubscription: { type: Boolean, required: true },
      hasPastDueInvoice: { type: Boolean, required: true },
    },
    {
      _id: false,
    },
  );

  const CustomerSchema = new mongoose.Schema(
    {
      username: { type: String, required: true },
      subscriptionsConfig: {
        type: SubscriptionsConfigSchema,
        required: true,
        default: SUBSCRIPTIONS_CONFIG_DEFAULT,
      },
    },
    {
      timestamps: true,
    },
  );

  const Test = mongoose.model('TestCustomer', CustomerSchema);

  const updatedDocument = await Test.findOneAndUpdate(
    { username: 'testUpsert' },
    { $set: { 'subscriptionsConfig.hasPaidSubscription': true } },
    { new: true, upsert: true, setDefaultsOnInsert: true },
  );

  console.log(updatedDocument);
}

Result:

MongoServerError: Updating the path 'subscriptionsConfig.hasPaidSubscription' would create a conflict at 'subscriptionsConfig'
    at Connection.onMessage (/Users/aprots/Projects/Royaltie/royaltie.crm.be/node_modules/mongodb/src/cmap/connection.ts:438:20)
    at MessageStream.<anonymous> (/Users/aprots/Projects/Royaltie/royaltie.crm.be/node_modules/mongodb/src/cmap/connection.ts:256:56)
    at MessageStream.emit (events.js:400:28)
    at MessageStream.emit (domain.js:475:12)
    at processIncomingData (/Users/aprots/Projects/Royaltie/royaltie.crm.be/node_modules/mongodb/src/cmap/message_stream.ts:193:14)
    at MessageStream._write (/Users/aprots/Projects/Royaltie/royaltie.crm.be/node_modules/mongodb/src/cmap/message_stream.ts:70:5)
    at writeOrBuffer (internal/streams/writable.js:358:12)
    at MessageStream.Writable.write (internal/streams/writable.js:303:10)
    at TLSSocket.ondata (internal/streams/readable.js:731:22)
    at TLSSocket.emit (events.js:400:28)
    at TLSSocket.emit (domain.js:475:12)
    at addChunk (internal/streams/readable.js:293:12)
    at readableAddChunk (internal/streams/readable.js:267:9)
    at TLSSocket.Readable.push (internal/streams/readable.js:206:10)
    at TLSWrap.onStreamRead (internal/stream_base_commons.js:188:23) {
  operationTime: new Timestamp({ t: 1660593999, i: 6 }),
  ok: 0,
  code: 40,
  codeName: 'ConflictingUpdateOperators',
  '$clusterTime': {
    clusterTime: new Timestamp({ t: 1660593999, i: 6 }),
    signature: {
      hash: new Binary(Buffer.from("6718dd844d79d3daa40815d3358e26fe02ddfd6a", "hex"), 0),
      keyId: new Long("7080913925792858116")
    }
  },
  [Symbol(errorLabels)]: Set(0) {}
}

Expected Behavior

New document created, based on: FilterQuery, subscriptionsConfig options in $set and default in Schema.

{
  _id: new ObjectId("62faa36a198ef0a8940ad53b"),
  username: 'testUpsert',
  __v: 0,
  createdAt: 2022-08-15T19:50:01.442Z,
  subscriptionsConfig: { hasPaidSubscription: true, hasPastDueInvoice: false },
  updatedAt: 2022-08-15T21:09:50.522Z
}
@IslandRhythms IslandRhythms added the confirmed-bug We've confirmed this is a bug in Mongoose and will fix it. label Aug 24, 2022
@IslandRhythms
Copy link
Collaborator

const mongoose = require('mongoose');

run().catch((err) => console.log(err));

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

  const SUBSCRIPTIONS_CONFIG_DEFAULT = {
    hasPaidSubscription: false,
    hasPastDueInvoice: false,
  };

  const SubscriptionsConfigSchema = new mongoose.Schema(
    {
      hasPaidSubscription: { type: Boolean, required: true },
      hasPastDueInvoice: { type: Boolean, required: true },
    },
    {
      _id: false,
    },
  );

  const CustomerSchema = new mongoose.Schema(
    {
      username: { type: String, required: true },
      subscriptionsConfig: {
        type: SubscriptionsConfigSchema,
        required: true,
        default: SUBSCRIPTIONS_CONFIG_DEFAULT,
      },
    },
    {
      timestamps: true,
    },
  );

  const Test = mongoose.model('TestCustomer', CustomerSchema);

  const updatedDocument = await Test.findOneAndUpdate(
    { username: 'testUpsert' },
    { $set: { 'subscriptionsConfig.hasPaidSubscription': true } },
    { new: true, upsert: true, setDefaultsOnInsert: true },
  );

  console.log(updatedDocument);
}

@mhassan1
Copy link

This may be caused by 25c7bce.

@vkarpov15 vkarpov15 added this to the 6.5.5 milestone Sep 1, 2022
vkarpov15 added a commit that referenced this issue Sep 7, 2022
fix(setDefaultsOnInsert): avoid applying defaults on insert if nested property set
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
4 participants