Just a quick question: Does MongoDB/Mongoose not allow you to add new property that wasn’t defined in the Schema?
I have an existing Schema:
const userSchema = new Schema({
username: { type: String, required: true },
});
Then I created a document:
User.create({ username: "vietan" })
Later in the code I want to add 2 new properties to said document:
User.findByIdAndUpdate(
id,
{ description: "This is a sentence", date: new Date() },
{new: true},
(err, updatedDoc) => { if (err) console.error(err) }
);
But this doesn’t work. I looked into mongoose’s docs but I couldn’t find anything relevant.
Also it said in the docs:
The query executes if callback
is passed.
What happens if I don’t pass the callback? I tried
console.log(User.findByIdAndUpdate(id, {username: "vietan"}, {new: true}))
but it just gives me an error.
By default, you can only create or update data for the fields defined in the schema. But, the insert or update doesn’t throw any error even if you try to include fields not defined in the schema.
To add new fields to the schema use the schema’ s add
method.
The code doesn’t give an error. When you don’t pass a callback the findByIdAndUpdate
returns a Query
object. You need to execute the query object for the update to complete (that is persist the update data).
User.findByIdAndUpdate(id, {username: "vietan"}, {new: true}).exec()
But, to see the update result (confirmation ) in your code, you still need to use the callback in the exec
, e.g.:
User.findByIdAndUpdate(id, {username: "vietan"}, {new: true}).exec((err. result) => {
if (err) throw err;
console.log('Update result:', result);
});
That said, you may as well pass the same callback to the findByIdAndUpdate
and be done with your update query without using exec
.