javascript 是否有将基于字符串的 JSON 转换为 Mongoose Schema 对象实例的本机功能?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12048093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a native feature to convert string based JSON into Mongoose Schema object instance?
提问by Renato Gama
I am using Express and I am looking for a convenient way to convert this kind of object (which comes on the request req.body.myObject
):
我正在使用 Express 并且我正在寻找一种方便的方法来转换这种对象(它来自请求req.body.myObject
):
{
"name": "Foo",
"someNumber": "23",
"someBoolean": "on"
}
Into an instance of this Schema:
进入这个 Schema 的一个实例:
var myObjectSchema = new Schema({
name: String,
someNumber: Number,
someBoolean: Boolean
});
Notice that the first object comes from the request, so its made entirely by Strings.
请注意,第一个对象来自请求,因此它完全由字符串构成。
Is there some nice way to achieve this? If not, would you have any suggestions on how to implement this feature as a middleware???
有什么好的方法可以实现这一目标吗?如果没有,您对如何将此功能实现为中间件有什么建议吗???
采纳答案by Renato Gama
By referring to this thread Mongoose : Inserting JS object directly into dbI figured out that yes, theres a built in feature for this.
通过参考这个线程Mongoose : Inserting JS object directly into db我发现是的,有一个内置的功能。
You simply build a new model passing request values (from the form) as parameters:
您只需构建一个新模型,将请求值(来自表单)作为参数传递:
function add(req, res){
new Contact(req.body.contact).save(function(err){
console.log("Item added");
res.send();
});
};
It automatically converts stuff for you!
它会自动为您转换内容!
回答by Ryan Wheale
I know this answer has already been accepted, but I wanted to point out that mongoose takes care of most of the casting for you... most of the time. While it's convenient that mongoose does this, it abstracts away the true behavior of mongo. For example, mongoose lets you do something like this:
我知道这个答案已经被接受了,但我想指出猫鼬会为你处理大部分的选角……大部分时间。虽然 mongoose 这样做很方便,但它抽象了 mongo 的真实行为。例如,猫鼬可以让你做这样的事情:
PersonModel.findById("4cdf00000000000000007822", ...);
However, if you tried to query the database directly (without mongoose), this would notwork:
但是,如果您想直接查询数据库(不包括猫鼬),这将不工作:
PersonCollection.find({_id: "4cdf00000000000000007822"}, ...);
This is because ObjectIds are not strings... they are objects. Internally, mongoose converts that string to an ObjectId and then performs a query against the database so that the final query looks kinda like this:
这是因为 ObjectIds 不是字符串……它们是对象。在内部,mongoose 将该字符串转换为 ObjectId,然后对数据库执行查询,以便最终查询看起来像这样:
PersonCollection.find({_id: ObjectId("4cdf00000000000000007822")}, ...);
Also, each path in a schema has a "caster" method. This is a private method, but it's darn handy when you need it. PLEASE NOTE THAT THE caster
METHODS DESCRIBED BELOW ARE UNDOCUMENTED AND CAN CHANGE WITHOUT WARNING. USE AT YOUR OWN RISK(sorry for yelling):
此外,模式中的每条路径都有一个“caster”方法。这是一种私有方法,但在您需要时非常方便。 请注意,下面caster
描述的方法没有记录,可以在没有警告的情况下更改。使用风险自负(抱歉大喊大叫):
// Use PersonModel.schema.paths() to get all paths and loop over them if you want
var key = "name";
var pathObj = PersonModel.schema.path( key );
if( !pathObj ) pathObj = PersonModel.schema.virtualpath( key );
if( !pathObj ) { /* not found: return, continue, exit, whatever */ }
// UNDOCUMENTED: USE AT YOUR OWN RISK
var caster = pathObj.caster || pathObj;
var castedValue = caster.cast( req.body.name );
Why do I know this? Because if you want to use some of the more advanced features of mongo such as aggregation, you will need to cast your own values as you build the pipeline. I have also needed to manually cast values for certain queries which used the $in
operator... maybe this is not needed any more. Point is, if you are having trouble getting the results you expect, try casting the values yourself.
为什么我知道这些?因为如果您想使用 mongo 的一些更高级的功能,例如聚合,您将需要在构建管道时投射自己的值。我还需要为使用$in
运算符的某些查询手动转换值......也许不再需要这样做了。重点是,如果您无法获得预期的结果,请尝试自己转换值。
回答by Mahn
Provided the schema is static, one could theoretically go the lazy, non-sophisticated way and just hardcode the values instead of passing the object itself:
如果模式是静态的,理论上可以采用懒惰的、非复杂的方式,只对值进行硬编码,而不是传递对象本身:
var someObject = {
name: "Foo",
someNumber: "23",
someBoolean: "on"
}
var myObjectSchema = new Schema({
name: someObject.name,
someNumber: parseInt(someObject.someNumber, 10),
someBoolean: (someObject.someBoolean == "on")
});
Possibly not the answer you were looking for, but might be something to consider if nothing better is available.
可能不是您正在寻找的答案,但如果没有更好的可用,则可能需要考虑。