是否有本机功能可将基于字符串的JSON转换为Mongoose Schema对象实例? [英] Is there a native feature to convert string based JSON into Mongoose Schema object instance?

查看:75
本文介绍了是否有本机功能可将基于字符串的JSON转换为Mongoose Schema对象实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Express,并且正在寻找一种方便的方法来转换这种对象(在请求req.body.myObject上出现):

{
  "name": "Foo",
  "someNumber": "23",
  "someBoolean": "on"
}

进入此架构的实例:

var myObjectSchema = new Schema({
    name: String,
    someNumber: Number,
    someBoolean: Boolean
});

请注意,第一个对象来自请求,因此它完全由字符串组成.

是否有一些不错的方法来实现这一目标?如果没有,您是否对如何将此功能作为中间件实现有任何建议?

解决方案

通过引用此线程

它会自动为您转换内容!

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):

{
  "name": "Foo",
  "someNumber": "23",
  "someBoolean": "on"
}

Into an instance of this 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 referring to this thread Mongoose : Inserting JS object directly into db I figured out that yes, theres a built in feature for this.

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!

这篇关于是否有本机功能可将基于字符串的JSON转换为Mongoose Schema对象实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆