Reputation: 449
The findByIdAndUpdate method should update or insert an object in the DB, but it does nothing. Nor it does throw an error message or something.
I also tried it with the original ObjectId as _id field, but doesn't work either.
Has anybody a clue what is missing to update or insert the object into the DB?
const schema = new Schema({
_id: {
type: Number,
required: true
},
name: {
type: String,
required: true
}
}, { toJSON: { virtuals: true } });
const myJson = {
"myobject": {
"_id": 781586495786495,
"name": "MyName"
}
}
const MyModel = mongoose.model('MyModel', schema);
MyModel.findByIdAndUpdate(myJson.myobject._id, myJson.myobject, { upsert: true });
Upvotes: 1
Views: 690
Reputation: 795
I used your code and it actually works as intended. The reason why it doesn't return any errors nor does anything might be that you're not connected to the database at the time you're executing the operation on the model.
Please consider the following snippet, it worked for me.
mongoose.connect('mongodb://localhost:27017/testingcollection').then(() => {
const schema = new mongoose.Schema({
_id: {
type: Number,
required: true
},
name: {
type: String,
required: true
}
}, { toJSON: { virtuals: true } });
const myJson = {
"myobject": {
"_id": 781586495786495,
"name": "MyName"
}
};
const MyModel = mongoose.model('MyModel', schema);
MyModel.findByIdAndUpdate(myJson.myobject._id, myJson.myobject, { upsert: true }).then(obj => {
mongoose.connection.close();
});
});
Upvotes: 1