Automattic / Automattic/mongoose

Protect against inserting documents with null `_id`

Open
#9,201 0 comments 2 reactions 0 assignees View on GitHub
discussion
Dominant language
JavaScript
Stars
27.5k
Forks
4k
Avg merge
2d 7h
Merged PRs (30d)
35

Description

For example, the below script (re: #9180) ends up upserting a document with a null `_id`:

```javascript
const mongoose = require('mongoose');
mongoose.set('debug', true);

const { Schema } = mongoose;

(async () => {
const dbUri = 'mongodb://localhost:27017/test';
const db = await mongoose.connect(dbUri, { useNewUrlParser: true });
await db.connection.dropDatabase();

const schema = new Schema({ name: String });
const model = mongoose.model('item', schema);

await model.bulkWrite([{
updateOne: {
filter: { _id: null },
update: { $set: { name: 'John Doe' } },
upsert: true,
},
}]);

console.log(await model.find());

await db.disconnect();
process.exit(0);
})();
```

A document with a null `_id` is technically valid, but many users may see that as a bug. Perhaps we should add some logic to protect against this, at least for Mongoose's default `_id`?

Contributor guide

Open the contributing guide

Research direction

Start by running the JavaScript reproduction in the issue against MongoDB and trace the bulkWrite upsert path it exercises. Identify the existing tests around bulk writes and default _id handling; done should mean the reported case no longer inserts a document with a null _id without breaking valid upserts.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, mongodb, node.js
Domain
database
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.