【问题标题】:Convert JSON to INTeger for MongoDB?将 JSON 转换为 MongoDB 的整数?
【发布时间】:2014-02-25 13:01:15
【问题描述】:

用.post的FORM数据到express/node.js

所有值当前都以字符串形式存储和返回

希望将其中一个数据值 (req.body.quantity) 存储为 INT

//POST
app.post('/add', function (req, res) {    

db.collection('demo').insert(

    {
        "title" : req.body.title,
        "quantity" : req.body.quantity,
    },

        function (err, doc) {

            getAll(res);

        });
});

getAll 当前如下所示:

//EXPRESS NODE.JS
function getAll(res) {

    db.collection('demo').find().sort( { quantity: 1 } ).toArray(function (err, docs) {

     // each doc should look like: { title: 'string', quantity: int}

        res.json({docs: docs});

    });
}

还有工作的.get:

// AJAX    
$('#getBtn').click(function() {
  $.get('http://localhost:9999').
   done(gotAllSuccess).
   fail(gotAllFailure);
});

【问题讨论】:

    标签: jquery ajax json node.js mongodb


    【解决方案1】:

    对于您的代码,我相信这会为您解决问题。

    "quantity" : parseInt(req.body.quantity)
    

    但是,如果您还没有,我建议您查看Mongoose 之类的内容。这是 MongoDB 的 ORM,它允许您定义描述模型外观的 schemas。在您的情况下,您可以设计如下所示的架构:

    // Define your schema somewhere where your app is first initialized.
    // You'll also want to open your db connection here somewhere as well, but I'll
    // let you figure that out. http://mongoosejs.com
    var demoSchema = new mongoose.Schema({ title: String, quantity: Number });
    var Demo = mongoose.model('Demo', demoSchema);
    // You can just pass in an object literal to mongoose.model instead of
    // instantiating a Schema object, but instantiating a Schema object is what
    // you'd have to do if you wanted to also add virtual methods/properties.
    

    您还可以在此处将virtual propertiesvirtual methods 添加到您的架构中。这些属性和方法不会存储在数据库中。

    那么你可以这样做:

    // Retrieve the model you created.
    var Demo = require('mongoose').model('Demo');
    
    // Request handler for POST requests to /add
    app.post('/add', function (req, res) { 
        // Create a new instance of your Demo model and populate it with data.
        var newDemo = new Demo({
            title: req.body.title,
            quantity: req.body.quantity
            // quantity will be converted to a Number because the schema defines it
            // as one.
        });
        // Mongoose documents have persistence methods on them, including save
        // which will update or insert the document depending on whether or not
        // it has an _id already.
        newDemo.save(function (err, newDemo) {
            if (err) return handleError(err);
            // Models also act as the API for querying. Here we find all documents,
            // sort them by quantity ascending, then execute the query.
            // Note: mongoose's query builder syntax below uses promises to make
            // queries very readable :)
            Demo.find().sort('quantity').exec(function (err, demos) {
                if (err) return handleError(err);
    
                // demos is an array of Demo instances, each with the same
                // persistence methods you saw above.
    
                // Each demo doc's properties will adhere to the defined type
                // in the schema.
                //
                // { title: 'hello', quantity: 123}
    
                res.json({ docs: demos });
            });
        });
    });
    

    【讨论】:

    • 非常酷的 Mongoose 简介。一直想知道如何潜入其中,这真的很有帮助!
    • @StackThis 如果你喜欢猫鼬,你可能也会喜欢我为它写的包装器mongoose-simpledb。 Simpledb 使得设置和使用 mongoose 变得非常容易:)
    • 所以基本上,当 newDemo 保存时(用于在 mongodb 中插入的 mongoose '快捷方式'),匿名函数(非常适合节点事件循环)会找到所有保存的 newDemo(现在 db 中的文档)按数量对它们进行排序,然后随后的 anonFunction 将所有演示文档呈现为 json 到 .get.. 是否正确?
    • 真的很整洁..一定会好好看看-simpledb
    • 还可以查看我的编辑。我用有用的 cmets 更新了代码示例。
    【解决方案2】:

    您可以使用Number(...) constructor or function

    Number("123"); // => 123
    
    db.collection('demo').insert(
      {
        "title" : req.body.title,
        "quantity" : Number(req.body.quantity),
      },
      // ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-04
      相关资源
      最近更新 更多