背景
问题是我想通过请求中传递的变量来访问对象的属性。发出 GET/modify/:var 请求来修改 MongoDB 中已保存文档的属性。要知道我们想要修改文档的哪个属性(在获取时转换为对象),我们需要在 :var 中传递的字符串。
路线
public modify(req: express.Request, res: express.Response, next: express.NextFunction)
{
Model.findOne({attr: true}, (err, result) => {
if (err) {
console.log(err);
}
else {
let copy = result;
copy.attr.one.(req.params.var) = false; // here
}
});
}
更新
在 Paul 回答之后,我编辑了代码,它返回了 500 状态代码。我编辑了
router.put('/route/:var')
public mock(req: express.Request, res: express.Response, next: express.NextFunction) {
Model.findOne({attr: false}, (err, doc) => {
doc.attr[req.params.var] = false;
model.save((e) => {
if (e){
console.log(e);
}
res.send(doc);
});
});
模型结构
export interface Model extends mongoose.Document {
attr: {
one: {value: Boolean},
two: {value: Boolean},
three: {value: Boolean},
four: {value: Boolean},
};
}
最佳答案
好吧,首先,您不应该使用 GET 请求来修改任何 GET 请求应该是查询的内容,而不更改服务器上的任何内容。
您正在寻找的是 PUT 请求,该请求用于修改现有资源。
其次,您尝试修改一个对象,但实际上还没有对象。你的 findOne 必须有一些可以查询的东西。如果您有一个类似 http://example.com/modify/name
的 URL,您预计会发生什么?无法知道您正在修改哪个名称或将其修改为什么。
即使您只是像您建议的那样执行 bool 运算,获取给定的 bool 变量并将其设置为 false,您的 URL 也不会告诉您哪个模型应该将此变量设置为 false。
相反,您可以将其设置为向(例如)/things/:thingId
发出 PUT 请求(其中 thingId 是您正在建模的任何给定事物的唯一标识符)。这将要求您的客户端在请求正文中发送所有可更新的属性。
或者,如果您希望只修改所选事物的一个属性,则可以将 PUT 设置为 /things/:thingId/:attr
。在这种情况下,您的处理程序将如下所示:
app.put('/things/:thingId/:attr', (req, res, next) => {
// note, I normally do this kind of thing in an `app.param()` or `router.param()` call. Included here for brevity.
Thing.findById(req.params.thingId, (err, thing) => {
thing[req.params.attr] = req.body[attr];
thing.save((e) => {
// todo: handle the error
res.send(thing);
});
});
});
正如我所说,这里的回调比我通常做的要嵌套更多一些,但希望您能了解总体思路。
关于node.js - Express.js 和 Mongoose : access Object attribute name by the request parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44462188/