NodeJS& Mongoose:将元素添加到现有的空数组

时间:2015-11-17 15:20:56

标签: arrays json node.js mongoose updatemodel

我正在构建一个NodeJS应用程序,用于根据MSQL数据库中的数据创建报告。所有应用程序相关数据都使用Mongoose存储在MongoDB中。我的猫鼬模型包含一个空数组,然后由用户通过Rest-API填充。 向阵列添加新元素时出错。我已经使用model.array.push(object); model.save()findByIdAndUpdate(...)进行了尝试。查找我的代码,包括以下两种不同的尝试:

Mongoose架构

var sqlSchema = mongoose.Schema({ // Schema to store information about SQL-procedures
    'name': String,
    'inputs': [
        {
            'name': String,
            'type': String,
            'value': String,
            'adjustable': Boolean
        }
    ]
});

REST API

我的应用程序通过POST接受'输入' -array的新元素:

var mongoose = require('mongoose'),
    SqlProcedure = mongoose.model('SqlProcedure');

// ...

router.post('/sql/:id/inputs', function(req, res) {
    SqlProcedure.findById(req.params.id, function(err, sql) {
        if(err) {
            res.send(msg.error('error retrieving sql-procedure', err));
        } else {
            if(sql.inputs.length > 0) {     // catch empty array
                for(var key in sql.inputs) {
                    if(sql.inputs[key].name == req.body.name) {
                        return res.send(msg.error('input already in inputs', err));
                    }
                }
            }

            var data = req.body;

            var input = {
                name: data.name,
                type: data.type,
                value: data.value,
                adjustable: data.adjustable
            };

            // attempt one or two
        }
    });
});

尝试一个:

            sql.inputs.push(input); // EXCEPTION 1

            sql.save(function(err) {
                // fancy errorhandling
                return res.send(msg.ok(sql));
            });

尝试两个:

            SqlProcedure.findByIdAndUpdate(req.params.id,
                {$push: {inputs: input}}, // EXCEPTION 2
                {safe: true, upsert: true},
                function(err, sql) {
                    // fancy errorhandling
                    res.send(msg.ok('input added to sql-procedure' + req.params.id));
                }
            );

例外

尝试一个:

throw new CastError('string', value, this.path);
  ^
Error
    at MongooseError.CastError (\node_modules\mongoose\lib\error\cast.js:18:16)
    at SchemaString.cast (\node_modules\mongoose\lib\schema\string.js:434:9)
    at Array.MongooseArray.mixin._cast (\node_modules\mongoose\lib\types\array.js:124:32)
    at Array.MongooseArray.mixin._mapCast (\node_modules\mongoose\lib\types\array.js:295:17)
    at Object.map (native)
    at Array.MongooseArray.mixin.push (\node_modules\mongoose\lib\types\array.js:308:25)
    at Query.<anonymous> (\app\api\sql_procedure.js:69:28)
    at \node_modules\mongoose\node_modules\kareem\index.js:177:19
    at \node_modules\mongoose\node_modules\kareem\index.js:109:16
    at doNTCallback0 (node.js:417:9)
    at process._tickCallback (node.js:346:13)

尝试二:

"stack": "Error
at MongooseError.CastError (\\node_modules\\mongoose\\lib\\error\\cast.js:18:16)
at SchemaArray.cast (\\node_modules\\mongoose\\lib\\schema\\array.js:156:15)
at SchemaArray.cast (\\node_modules\\mongoose\\lib\\schema\\array.js:167:17)
at Query._castUpdateVal (\\node_modules\\mongoose\\lib\\query.js:2384:22)
at Query._walkUpdatePath (\\node_modules\\mongoose\\lib\\query.js:2298:27)
at Query._castUpdate (\\node_modules\\mongoose\\lib\\query.js:2227:23)
at castDoc (\\node_modules\\mongoose\\lib\\query.js:2430:18)
at Query._findAndModify (\\node_modules\\mongoose\\lib\\query.js:1752:17)
at Query._findOneAndUpdate (\\node_modules\\mongoose\\lib\\query.js:1620:8)
at \\ITZReport\\node_modules\\mongoose\\node_modules\\kareem\\index.js:156:8
at \\node_modules\\mongoose\\node_modules\\kareem\\index.js:18:7
at doNTCallback0 (node.js:417:9)\n    at process._tickCallback (node.js:346:13)",
    "message": "Cast to undefined failed for value \"[object Object]\" at path \"inputs\"",
    "name": "CastError",
    "value": [
        {
            "adjustable": "true",
            "value": "Harry Potter",
            "type": "String",
            "name": "salesman"
        }
    ],
    "path": "inputs"

要插入的数据

{ name: 'salesman',
  type: 'String',
  value: 'Harry Potter',
  adjustable: 'true' }

我是NodeJS和mongoose的新手并试图在我自己解决这个问题很长时间。如果那里的任何人可以帮助我,那将是很棒的!

提前致谢, dj2bee

更新

我想我应该澄清用户与REST-API交互的过程:

  1. 用户通过传递值来创建新记录 name。此时设置了nameinputs - 数组 是空的。
  2. 在下一步中,用户将新记录添加到 inputs - 逐个数组。 name保持不变 新的inputs已添加到数组中。
  3. 用户应该能够编辑或删除条目 inputs - 阵列
  4. adjustable的数据类型更改为String未进行任何更改。我也尝试过硬编码属性而不是通过HTTP-POST传递它们 - 仍然是同样的例外。

2 个答案:

答案 0 :(得分:1)

您应该将数据插入

{ name: 'salesman', 
  inputs: [{name: 'salesman',
  type: 'String',
  value: 'Harry Potter',
  adjustable: true}]}

即。如果没有引号和输入作为数组

,则为true

或者在架构中调整为String,并在模型定义中删除输入为数组

var sqlSchema = mongoose.Schema({ // Schema to store information about SQL-procedures

            'name': String,
            'type': String,
            'value': String,
            'adjustable': String
        });

答案 1 :(得分:0)

在网上搜索并测试代码中最奇怪的东西几个小时后,我找到了解决方案: 您无法为字段命名&#39;键入&#39;在mongoose-schema中。那就是它。

正确的代码如下所示:

Mongoose架构

var sqlSchema = mongoose.Schema({
    'name': String,
    'inputs': {
        'name': String,
        'datatype': String, // you can't name this field 'type'
        'value': String,
        'adjustable': Boolean
    }
});

REST API

router.post('/sql/:id/inputs', function(req, res) {
    SqlProcedure.findById(req.params.id, function(err, sql) {
        if(err) {
            res.send(msg.error('error retrieving sql-procedure', err));
        } else {
            if(!sql) {
                return res.send(msg.error('no sql-procedure found with id '
                    + req.params.id, null));
            }
            // check for duplicates

            var data = req.body;

            var input = {
                'name': data.name,
                'datatype': data.type,
                'value': data.value,
                'adjustable': data.adjustable
            };

            SqlProcedure.findByIdAndUpdate(req.params.id,
                {$push: {inputs: input}},
                {safe: true, upsert: true},
                function(err, sql) {
                    // fancy error handling
                }
            );
        }
    });
});