I have the following Schema defined:
var mongoose = require('mongoose');
var VenueSchema = new mongoose.Schema({
name: String,
email: String,
phone: String,
address: {address1: String, address2: String, suburb: String, state: String, postCode: Number, country: {type: String, default: 'Australia'}},
ABN: String,
website: String,
openingHours: [{order: Number, day: Date, open: String, close: String}],
closedDays: [{startDate: Date, endDate: Date}],
supportEmail: String
});
var Venue = mongoose.model('Venue', VenueSchema);
module.exports = Venue;
And I have the following method defined in Express to save the document:
app.post('/api/venues/:id', function (req, res) {
Venue.findOneAndUpdate({_id: req.params.id}, req.body, {upsert: true, new: true}, function (err, venue) {
if (err) {
res.status(500).send(err);
}
else {
res.status(200).json(venue);
}
});
});
The problem is, when the document contains an openingHours
array, the resulting saved document looks like this in the mongo
console:
"openingHours" : [
{
"_id" : ObjectId("563be68ce65bf8543c6ec5e0")
}
],
I can confirm, the object is being passed to the Express method, as req.body.openingHours
has the correct length and object within. And obviously something is happening, otherwise Mongo
would not have the _id
file populated, however, I don't understand why that is even happening. I have not defined a separate schema for this, it is simply an array of objects embedded within the doc.
There must be something simple which I am missing?
UPDATE
If I change the code withing my Express
method to the following:
Venue.update({_id: req.params.id}, req.body, {multi: true}, function (err, raw) {
if (err) {
res.status(500).send(err);
}
else {
Venue.findById(req.params.id, function(err, venue) {
if (err) {
res.status(500).send(err);
}
else {
res.status(200).json(venue);
}
});
}
});
Then my mongo
console looks like this:
"openingHours" : [
{
"order" : 0,
"day" : "Monday",
"open" : "10:00",
"close" : "22:00",
"_id" : ObjectId("563bf15ac16e007832e025ae")
},
{
"order" : 1,
"day" : "Tuesday",
"open" : "10:00",
"close" : "22:00",
"_id" : ObjectId("563bf197c16e007832e025af")
},
{
"order" : 2,
"day" : "Wednesday",
"open" : "10:00",
"close" : "22:00",
"_id" : ObjectId("563bf19bc16e007832e025b0")
}
],
Now I dont understand 2 things:
1. Why does mongo
treat objects embedded in arrays differently to plain old embedded objeects? i.e. the embedded address
object does not have an _id
field assigned to it when you save or update.
2. Why does findOneAndUpdate
behave so differently? Is it because of {multi: true}
?