Automattic / Automattic/mongoose

Setting and getting fields not defined in schema not working by using document's set() and get()

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

Description

**Do you want to request a *feature* or report a *bug*?**
*bug*

**What is the current behavior?**
Was based on the solution on https://github.com/Automattic/mongoose/issues/5378 but setting a field with `doc.set(fields, undefined, {strict: false}` and saving the document doesn't remove the field from the document in database. Also tried while debugging to evaluate the `doc.get(field)` method and it returns undefined.

**If the current behavior is a bug, please provide the steps to reproduce.**
```javascript
async function copyUserData() {
let users = await User.find({userData: null});
let userDataSchemaFields = utils.database.getSchemaFields(UserData);
let userSchemaFields = utils.database.getSchemaFields(User);
let userDataObject;
let userData;
for (const user of users) {
userDataObject = {};
for (const schemaField of userDataSchemaFields) {
if (user._doc[schemaField] && userSchemaFields.indexOf(schemaField) < 0) {
userDataObject[schemaField] = user._doc[schemaField];
user.set(schemaField, undefined, {strict: false});
}
}
userData = await UserData.create(userDataObject);
user.userData = userData._id;
await user.save();
}
}

copyUserData()
.then(() => {
console.log("Successfully separated the user data");
})
.catch((err) => {
console.err("UserData creation error: " + err);
});
```

**What is the expected behavior?**
I was expecting to remove the fields set as `undefined` from the database. I did put the full code (except for the external utility but that just returns an array of fields) just to be sure that something is not wrong.

**Please mention your node.js, mongoose and MongoDB version.**
mongoose: 5.4.5
MongoDB: 3.4
Node.js: 8.12.0

Contributor guide

Open the contributing guide

Research direction

Start with the provided copyUserData reproduction using the stated Mongoose, Node.js, and MongoDB versions, focusing on document set(), get(), and save() behavior for undefined fields with strict mode disabled. Done means reproducing the issue and confirming that fields set to undefined are removed from the persisted document, with a regression test covering that behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, mongodb, node.js
Domain
backend, databases
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.