[英]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.