Mongoose : Inserting JS object directly into db

15,906

If you use a plugin like this with mongoose (http://tomblobaum.tumblr.com/post/10551728245/filter-strict-schema-plugin-for-mongoose-js) you can just put together an array in your form, like newitem[item_title] and newitem[item_abv] -- or item[title] and item[abv]

You could also just pass the whole req.body if the elements match up there. That MongooseStrict plugin will filter out any values not explicitly set in your schema, but it still leaves checking types and validation up to mongoose. With proper validation methods set in your schema, you will be safe from any injection attacks.

EDIT: Assuming you have implemented the plugin, you should be able to use this code.

app.post('/items/submit/new-item', function(req, res){
  new itemModel(req.body.formContents).save(function (e) {
    res.send('item saved');
  });
});
Share:
15,906

Related videos on Youtube

wilsonpage
Author by

wilsonpage

Follow Me on Twitter: @wilsonpage

Updated on June 18, 2022

Comments

  • wilsonpage
    wilsonpage almost 2 years

    Ok so I have a JS object that is being POSTed via AJAX to the nodejs backend. I want to insert this js object directly into my mongoose db as the object keys already match up perfectly with the db schema.

    I currently have this (not dynamic and overly complex):

    app.post('/items/submit/new-item', function(req, res){
        var formContents = req.body.formContents,
            itemModel = db.model('item'),
            newitem = new itemModel();
    
        newitem.item_ID         = "";
        newitem.item_title      = formContents.item_title;
        newitem.item_abv        = formContents.item_abv;
        newitem.item_desc       = formContents.item_desc;
        newitem.item_est        = formContents.item_est;
        newitem.item_origin     = formContents.item_origin;
        newitem.item_rating     = formContents.item_rating;
        newitem.item_dateAdded  = Date.now();
    
        newitem.save(function(err){
            if(err){ throw err; }
            console.log('saved');
        })
    
        res.send('item saved');
    });
    

    But want to trim it down to something like this (sexy and dynamic):

    app.post('/items/submit/new-item', function(req, res){
        var formContents = req.body.formContents,
    
        formContents.save(function(err){
            if(err){ throw err; }
            console.log('saved');
        })
    
        res.send('item saved');
    });
    
    • T.J. Crowder
      T.J. Crowder over 12 years
      "Ok so I have a JS object that is being POSTed via AJAX to the nodejs backend. I want to insert this js object directly into my mongoose db as the object keys already match up perfectly with the db schema." Sounds like an excellent vector for some kind of injection attack, similar to SQL injection. Always better to process and validate your data on the server before sending it. Clients cannot be trusted.
    • wilsonpage
      wilsonpage over 12 years
      Yes I know. This is a test case. That was not my question.
    • Sam Vloeberghs
      Sam Vloeberghs about 10 years
      So it's a bad test case, as you should ALWAYS validate data :) I'm currently working in a similar context and successfully tested validate.js to validate the data
  • wilsonpage
    wilsonpage over 12 years
    thanks the method you described worked without requiring the plugin. I will definately need to implement it at a further date to ensure security though. What is the point in schemas if they can be overridden like this? What other methods of input validation would you suggest?
  • Thomas Blobaum
    Thomas Blobaum over 12 years
    Schemas do a lot in mongoose, most importantly they save types properly into mongodb but they also let you setup validation, defaults, and other ODM stuff. At the moment the top level of a mongoose doc is essentially treated like the type "Mixed" (which accepts anything and only does stuff when the property updated matches a property in the schema) -- the plugin forces mongoose to only accept properties in the schema
  • wilsonpage
    wilsonpage over 12 years
    Coming from a mySQL background I am struggling to understand mongoose fully. The docs are not that clear to me. Could you recommend some resources or examples. I'm not looking to do anything advanced.
  • Thomas Blobaum
    Thomas Blobaum over 12 years
    The google group is a good place to start, and you can usually find help on irc pretty quickly in #node.js on freenode.net
  • Ron Wertlen
    Ron Wertlen about 11 years
    The schemas can contain validation code that is automatically executed -- i.e. hidden -- in your save() call. That is the beauty of mongoose, in one line, you have validated your user input and saved it off to the DB. You can also sanitize and change the input, by hooking into the model .pre() which can filter the user input for malicious input. Your line of code will remain the same, but the schema automatically filters + validates...
  • regretoverflow
    regretoverflow almost 11 years
    @ThomasBlobaum, your link has rotted, do you have that plugin on github, or is it obsoleted by mongoose built-ins?
  • Thomas Blobaum
    Thomas Blobaum almost 11 years
    @NikMartin schemas are strict by default now
  • regretoverflow
    regretoverflow almost 11 years
    @ThomasBlobaum Thanks for that info, I'm just getting into mongoose as well.
  • regretoverflow
    regretoverflow almost 11 years
    @ThomasBlobaum do you mind if I edit your answer? Finding outdated info on these sites drives me crazy when I'm searching. That's how I got to this answer, only to discover it's usurped.