Mongoose:将JS对象直接插入到数据库中 [英] Mongoose : Inserting JS object directly into db

查看:616
本文介绍了Mongoose:将JS对象直接插入到数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我有一个JS对象,通过AJAX被发布到nodejs后端。我想将这个js对象直接插入到我的mongoose数据库中,因为对象键已经与db模式完全匹配了。

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.

我目前有这个(没有动态和过于复杂):

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');
});

但是要将其修剪成如此(性感和动态):

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');
});


推荐答案

如果您使用这样的插件与mongoose a href =http://tomblobaum.tumblr.com/post/10551728245/filter-strict-schema-plugin-for-mongoose-js =nofollow noreferrer> http://tomblobaum.tumblr.com/post / 10551728245 / filter-strict-schema-plugin-for-mongoose-js ),你可以在窗体中放置一个数组,例如 newitem [item_title] newitem [item_abv] - 或 item [title] item [abv] / code>

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]

如果元素匹配,您也可以传递整个 req.body 。 MongooseStrict插件将过滤掉您的模式中未显式设置的任何值,但仍然会将检查类型和验证保留为mongoose。通过在您的模式中设置正确的验证方法,您将无需注射攻击。

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.

编辑:假设您已经实现了插件应该可以使用这段代码。

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');
  });
});

这篇关于Mongoose:将JS对象直接插入到数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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