Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a native feature to convert string based JSON into Mongoose Schema object instance?

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???

like image 811
Renato Gama Avatar asked Aug 21 '12 03:08

Renato Gama


People also ask

Which property of Mongoose will help us create a model object?

By default, Mongoose adds an _id property to your schemas. const schema = new Schema(); schema.path('_id'); // ObjectId { ... } When you create a new document with the automatically added _id property, Mongoose creates a new _id of type ObjectId to your document.

What is Mongoose ODM?

What is Mongoose? Mongoose is a Node. js-based Object Data Modeling (ODM) library for MongoDB. It is akin to an Object Relational Mapper (ORM) such as SQLAlchemy for traditional SQL databases. The problem that Mongoose aims to solve is allowing developers to enforce a specific schema at the application layer.

What is schema types ObjectId?

Schema. Types. ObjectId and that's means, it looks like a string of an ID when you get it back from the database but it's not, it's actually an object that converts it to a string.


1 Answers

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!

like image 150
Renato Gama Avatar answered Oct 06 '22 00:10

Renato Gama