Mongoose : Inserting JS object directly into db

后端 未结 1 1943
遇见更好的自我
遇见更好的自我 2021-01-02 14:59

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 u

相关标签:
1条回答
  • 2021-01-02 15:30

    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');
      });
    });
    
    0 讨论(0)
提交回复
热议问题