【发布时间】:2017-06-06 01:23:21
【问题描述】:
我一直在关注有关创建 RESTful API 的 Youtube 教程(我刚刚开始掌握这个领域)。本教程是关于书籍的,但我想扩展它以支持 geoJSON,因为这是我的最终目标。
如果字段位于文档的根目录,我可以毫无问题地更新字段,例如:
first_name: object.first_name,
我不明白的是如何更新作为子文档的一部分存在的字段:
geometry: { coordinates: [] },
我尝试过使用geometry.coordinates 和上述结构,它们都有效。
这是我所拥有的:
从对象模型更新函数
// 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.js 中的应用 put 函数
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 来自网络的请求
{
"geometry":
{
"type": "Point",
"coordinates": [-90.5299938027191, 24.42859997065679]
},
"properties":
{
"icon": "bar-15",
"title": "Bar",
"description": "A Bar"
}
}
HTTP 响应
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
示例 mongo 对象
{
"_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)
}
【问题讨论】:
标签: node.js mongodb rest mongoose