Trying to delete/set null a field with findOneAndUpdate
See original GitHub issueI’m trying to delete (also setting it to null would be acceptable as a backup plan) the field “board” from a document that looks like this:
var cardSchema = new Schema({
title: {
type: String,
required: true
},
version: {
type: Number,
required: true,
"default": 0
},
board: {
type: ObjectId,
ref: 'Board'
},
},{strict: false});
mongoose.model('Card', cardSchema);
For my scenario, I need to use the function findOneAndUpdate in the following way:
var cardChanges = {board: undefined, version: 10};
Card
.findOneAndUpdate({_id: "my_id"}, cardChanges,
{"new": true, upsert: false, passRawResult: false,
"overwrite": false, runValidators: true,
setDefaultsOnInsert: true})
.exec(function(err, result) {
if(err) {
// error handlers
}
if(!result) {
// No card to be updated
}
// ok
});
Before the update I have the document:
{
_id: "my_id",
title: "This is my card",
board: "my_board",
version: 9
}
And after:
{
_id: "my_id",
title: "This is my card",
board: "my_board",
version: 10
}
I tried to set the board with both null and undefined, the result is the same. For my use case I can’t use the save method. Mongoose 4.5.5, MongoDB 3.2.9 Any idea or workaround?
Thanks
Issue Analytics
- State:
- Created 7 years ago
- Comments:14
Top Results From Across the Web
Mongoose findOneAndUpdate with undefined set as null
I would expect that when I set a value to undefined it should remove the current item, So if I had for example...
Read more >db.collection.findOneAndUpdate() — MongoDB Manual
Creates a new document if no documents match the filter . For more details see upsert behavior. Returns null after inserting the new...
Read more >Mongoose v6.8.2: API docs
Set to false to disable buffering on all models associated with this connection. [options.dbName] «String» The name of the database you want to...
Read more >How to Use Mongoose's findOneAndUpdate Function
const Character = mongoose.model('Character', Schema({ name ; // If you set the `new` option to `true`, Mongoose will // return the document with ......
Read more >Extensions Overview - KMongo
Insert, Update & Delete¶. Insert¶. Note that by default, KMongo serializes null values during insertion of instances with the Jackson mapping engine. This...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
var cardChanges = { $set: { version: 10 }, $unset: { board: 1 } }
try that as a workaroundHappy to help 👍