2013-10-31 38 views
0

所以我想弄清楚如何在命令列表中保存多個命令,但我試過的所有東西都沒有工作。這是我有它成立至今,但是當它保存,它的如何獲得這個嵌套的模式在Mongoose中工作?

"command_list" : [ { "action" : "goto,goto", "target" : "http://www.google.com,http://www.cnn.com" } ] 

的格式保存時,我真的希望是這樣

"command_list" : [ "command" : { "action" : "goto", "target" : "http://www.google.com" },      
        "command" : { "action" : "goto", "target" : "http://www.cnn.com" } ] 

在有多個命令。到目前爲止,我app.js的存儲數據這樣

var configSample = new Configurations({ 
     command_list_size: request.body.command_list_size, 
     command_list: [ {action: request.body.action, target: request.body.target}] 
}); 

和模型看起來像這樣

var mongoose = require("mongoose"); 

var command = mongoose.Schema({ 
    action: String, 
    target: String 
}); 

var configSchema = mongoose.Schema({ 
    command_list_size: Number, 
    command_list: [command] 
}); 


module.exports = mongoose.model('Configurations', configSchema); 

那麼,如何獲取築巢行動去?謝謝!

回答

0

看起來你不會在將數據發送到服務器時打包數據。如果您使用以下命令:

command_list: [ {action: request.body.action, target: request.body.target}] 

這將抓住所有的行動和他們混爲一談一起做同樣的目標。文件已經嵌套在服務器上了,最好將數組發送到服務器。

另一種選擇是解析數據,以便在服務器上收到數據後將其拉出,但我認爲將它打包放在首位會更容易。

此外:

如果你想拆你有什麼,你可以使用String.split()方法和重建對象:

// not certain the chaining will work like this, but you get the idea. It works 
// on the string values you'll receive 
var actions = response.body.action.split(','); 
var targets = response.body.target.split(','); 

// the Underscore library provides some good tools to manipulate what we have 
// combined the actions and targets arrays 
var combinedData = _.zip(actions, targets); 

// go through the combinedData array and create an object with the correct keys 
var commandList = _.map(combinedData, function(value) { 
    return _.object(["action", "target"], value) 
}); 

可能有更好的方法來創建新的對象,但這個伎倆。

編輯:

我創建了一個問題,關於嘗試to refactor the above code here.