2016-02-26 60 views
0

這是我的架構使用Mongoose和Node將數據插入數組時出錯?

var mongoose  = require('mongoose'); 
var Schema  = mongoose.Schema; 

var FoodSchema = new mongoose.Schema({ 
title: String, 

comments: [{ 
    text: String 

}] 
}); 
module.exports = mongoose.model('Food', FoodSchema); 

如何張貼在評論中值,我已經試過這

router.route('/food') 


.post(function(req, res) { 

    var food = new Food();  
    food.title = req.body.title; 
    food.comments.text= req.body.comments[0].text; 

    food.save(function(err) { 
     if (err) 
      res.send(err); 

     res.json({ message: 'Successful'}); 
    }); 

    }) ; 

標題被插入,而不是評論

Postman snapshot

回答

0

Mongoose subdoc,請嘗試插入通過.push SUBDOCS如下

food.comments.push({text: req.body.comments[0].text}); 
+0

是的,它工作! :) thanx – MrRobot9

0

您可以使用下面的

"comments" :[{"text" : "comment1", "text" : "comment2"}] 
+0

如何訪問「comment2」?是不是評論[1] .text? – MrRobot9

+0

是的,這是做它的方式。 – Hbargujar

0

從客戶端(請求),通過這樣的評論:{"comments": [{"text": "Comment 1"}, {"text": "Comment 2"}, {"text": "Comment 3"}]}

而在你的代碼中,你可以像這樣保存:food.comments = req.body.comments

相關問題