繁体   English   中英

使用Mongoose和Node将数据插入数组时出错?

[英]Error in inserting data into an array using Mongoose and 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'});
    });

    }) ;

插入标题,但不插入注释

邮递员快照

您可以使用以下

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

每个Mongoose subdoc ,请尝试通过.push插入子文档,如下所示

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

从客户端(请求)传递这样的注释: {"comments": [{"text": "Comment 1"}, {"text": "Comment 2"}, {"text": "Comment 3"}]}

在您的代码中,您可以像这样保存它: food.comments = req.body.comments

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM