Reputation: 1130
I've been following a Youtube tutorial on creating a RESTful API (I'm just getting to grips with this field). The tutorial is about books, but I wanted to extend it to support geoJSON as that's my end goal.
I have no problem updating fields if they're at the root of the document such as:
first_name: object.first_name,
What I don't understand is how to update fields that exist as part of a subdocument:
geometry: { coordinates: [] },
I've tried using geometry.coordinates and the above structure, nether of which have worked.
Here's what I have:
Update Function from object model
// Update Object
module.exports.updateObject = function(id, object, options, callback)
{
var query = { _id: id};
var update = {
geometry:
{
type: object.geometry.type,
coordinates: object.geometry.coordinates
},
properties:
{
icon: object.properties.icon,
title: object.properties.title,
description: object.properties.description
}
}
User.findOneAndUpdate(query, update, options, callback);
};
app put function from app.js
app.put('/api/objects/:_id', function(req, res)
{
var id = req.params._id
var object = req.body;
Object.updateObject(id, object, {}, function(err, object)
{
if (err)
{
res.json(err);
}
res.json(object);
});
});
PUT Request from web
{
"geometry":
{
"type": "Point",
"coordinates": [-90.5299938027191, 24.42859997065679]
},
"properties":
{
"icon": "bar-15",
"title": "Bar",
"description": "A Bar"
}
}
HTTP Response
200 OK
Date: Fri, 20 Jan 2017 23:24:58 GMT
ETag: W/"4-N6YlnMDB2uKZp4Zkid/wvQ"
Connection: keep-alive
X-Powered-By: Express
Content-Length: 4
Content-Type: application/json; charset=utf-8
null
Example mongo object
{
"_id": ObjectId("58815cd0110dcc3b1e51d411"),
"geometry": {
"type": "Point",
"coordinates": [
-82.52920651436,
49.428099941567
]
},
"properties": {
"icon": "bar-15",
"title": "Bar",
"description": "A Bar",
"date": ISODate("2017-01-20T00:41:52.830Z")
},
"__v": NumberInt(0)
}
Upvotes: 0
Views: 872
Reputation: 1130
Found the issue:
I C+P'd the code from another part of my code and failed to noice that I hadn't updated the following line:
User.findOneAndUpdate(query, update, options, callback);
to:
Object.findOneAndUpdate(query, update, options, callback);
Upvotes: 0
Reputation: 11786
You can use $set
to update non root fields
User.findOneAndUpdate({
_id: id
}, {
$set: {
geometry: {
type: object.geometry.type,
coordinates: object.geometry.coordinates
},
properties: {
icon: object.properties.icon,
title: object.properties.title,
description: object.properties.description
}
}
}, {
new: true
}, (err, doc) => {
console.log('err', err);
console.log('doc', doc);
});
Upvotes: 1