2017-02-23 95 views
0

我第一次使用Mongo,並且在創建具有數組的文檔時遇到困難。 該對象被傳遞到的NodeJS服務器,像這樣:Mongoose - 將數組插入到mongo DB

{ 
"customerid":"121212", 
"name": "Zero 2679", 
"email": "[email protected]", 
"address": "bla bla bla", 
"tokens":[{"ctoken":"123456"},{"ctoken":"1234567"}] 
} 

代碼執行:

  var newCustomer = new Customer(
      { 
       _id: request.body.customerid, 
       name: request.body.name, 
       email: request.body.email, 
       address: request.body.address, 
       tokens:request.body.tokens 
      }); 
      newCustomer.save(function (err) { 
       if (err) winston.log('error', err); 
       // saved! 
      }) 

架構配置像這樣:

var customerSchema = new Schema({ 

// index: true => Tells mongo to index this paramater because it is used frequently. It makes querying faster 
_id: {type: String, unique: true}, // unique customer ID 

name: {type: String, default: '', required: true}, // Customer name 

//email: {type: mongoose.SchemaTypes.Email, required: true}, 
email: {type: String, required: true}, 

address: { type: String, required: true }, 

toknes: [{ ctoken :{type: String} }] 

}, {collection: 'customers'}); 

當我去看看MongoDB中的對象,它看起來像這樣:

{ 
"_id": "121212", 
"email": "[email protected]", 
"address": "bla bla bla", 
"tokens": [], 
"name": "Zero 2679", 
"__v": 0 
} 

令牌丟失,並有'_v'值,我甚至沒有。

請告知我做錯了什麼?

+1

_v是來自mongo,不用擔心 –

回答

1

tokens: [{ ctoken : String }]

request.body.tokens必須像= {ctoken: 'some string'}

 var newCustomer = new Customer(
     { 
      _id: request.body.customerid, 
      name: request.body.name, 
      email: request.body.email, 
      address: request.body.address, 
      tokens:[request.body.tokens] 
     }); 
     newCustomer.save(function (err) { 
      if (err) winston.log('error', err); 
      // saved! 
     }) 

,如果客戶DB文件中包含的數據,然後您應該執行push操作

+0

試過這個,仍然不起作用。請看看我更新的問題。 –

+1

在模式中有'toknes'字段而不是'tokens',做一個'console.log(req.body.tokens)' –

+0

4,一個錯字,我簡直不敢相信。 –

0

在您的模式應該是:

tokens: [{ type: String }] 

由於ctoken不是數據類型。工作模式如下圖所示:

架構中的
var customerSchema = new Schema({ 
_id: {type: String, unique: true}, 
name: {type: String, default: '', required: true}, 
email: {type: String, required: true}, 
address: { type: String, required: true }, 
tokens: [{ type: String }] 
}, {collection: 'customers'}); 
+0

試過這個,還是不行。請看看我更新的問題。 –