将JSON对象推入Mongoose数组

时间:2015-11-09 13:39:30

标签: javascript json node.js mongodb express

我是Mongoose的新手。我的目标是能够将数据推送到Mongoose数组,所以我可以在以后循环它: 这是我的架构:

var moduleSchema = new mongoose.Schema({
  name: {type: String, index: {unique: true}},
  priority: Number,
  author: String,
  enabled: Boolean,
  keywords: [{keyword: String}],
  code: String
});

我希望能够以这种格式向快递发送一个JavaScript对象,并将其插入自己的"关键字"领域。理想情况下,输出应如下所示:

{
    "_id": "56401885bff833582442bb5f",
    "name": "ModName",
    "priority": 1,
    "author": "tscrip",
    "enabled": true,
    "code": "TEST",
    "__v": 0,
    "keywords": [
        {
            "keyword": "Dog",
            "keyword": "Cat"
        }
     ]
}

每次我PUT数据更新时,我都会得到:

0:D,
1:O,
2:G

或者我得到:

The argument to $each in $push must be an array but it was of type Object

以下是我更新模型的代码:

if(req.body.keywords) updateObj.keywords = JSON.parse(req.body.keywords);

var keywordsArr = updateObj.keywords;
Module.findByIdAndUpdate({
    "_id": req.params.id
    },
    { $set: {keywords: { $each: { keyword: {keywordsArr}}}}},
    function(err, numAffected){
        console.log(err);
    }
); 

我发送一个简单的JSON对象进行更新:

{
    "keywords": [
        "mouse",
        "bird"
    ]
}

非常感谢任何帮助。

更新1

我试图让它成为一个数组:

var moduleSchema = new mongoose.Schema({
name: {type: String, index: {unique: true}},
priority: Number,
author: String,
enabled: Boolean,
keywords: [String],
code: String
});

并像这样更新:

if(req.body.keywords) updateObj.keywords = JSON.parse(req.body.keywords);
var keywordsArr = updateObj.keywords.keywords;
console.log(keywordsArr);
Module.findByIdAndUpdate({
    "_id": req.params.id
    },
    { $push: {keywords: {$each: keywordsArr}}},
    function(err, numAffected){
        console.log(err);
    }
);

但我现在收到错误:

{ [MongoError: exception: The field 'keywords' must be an array but is of type Object in document {_id: ObjectId('56401885bff833582442bb5f')}]
name: 'MongoError',
message: 'exception: The field \'keywords\' must be an array but is of type Object in document {_id: ObjectId(\'56401885bff833582442bb5f\')}'

1 个答案:

答案 0 :(得分:0)

将对象推送到数组Mongoose:

我的MongoDB或Mongoose Schema是这样的:

{
"_id": {
    "$oid": "5511241323214"
},
"target": "200",
"region": "United Kingdom",
"fullname": "John Smith",
"milesLog": [
    {
        "miles": "1",
        "activity": "Walking",
        "month": "Apirl 2015",
        "_id": {
            "$oid": "5527d"
        },
        "date": {
            "$date": "2015-04-10T13:53:43.549Z"
        }
    },
    {
        "month": "March 2015",
        "activity": "Walking",
        "miles": "1",
        "_id": {
            "$oid": "5527d9"
        },
        "date": {
            "$date": "2015-04-10T14:07:37.004Z"
        }
    }
]
"__v": 0
}

以下是我用来将数据推送到数组中的代码。 Mongoose带有内置" findByIdAndUpdate"功能

app.put('/user/:id', function(req, res) {

// Using mongoose in-built function "findbyID"
User.findById(req.params.id, function(err, provider) {

     // If error show.
     if (err)
     {
        res.send(err);
     }

// Using mongoose "findbyIDandUpdate" fucntion to "PUT" data into the array           
User.findByIdAndUpdate(

provider.id,
{$push: {"milesLog": 
{
    // Passing Data
    miles: req.body.miles,
    activity: req.body.activity,
    month:  req.body.month

}}},

{safe: true, upsert: true},

function(err, model) 
{
    console.log(err);
},

   // Response to send to User data as JSON 
  res.json(provider)
);

// Saving Data into MongoDB        
provider.save(function(err) 
{
      if (err)
      {
         res.send(err);
      }
});

});
});