【问题标题】:How to insert or delete data into mongodb collections in existing array for nodejs API?如何在 nodejs API 的现有数组中的 mongodb 集合中插入或删除数据?
【发布时间】:2021-07-29 23:47:50
【问题描述】:

你很好,我想我可以在这里找到合适的解决方案。我有简单的 mongoDB 和 Node Js API。所以我的问题是在我的数据库集合中有多个产品,每个产品都有一个 review 数组。当我尝试更新或删除评论数组元素中的任何数据时,它会在控制台中显示消息“记录添加为{ ok:0,n:0,nModified:0}”。但我想成功地将数据插入和删除到评论数组中。请看下面我的功能和方法:

路线:

app.put('/notes/insertarray', notes.insertToArray);

对于控制器:

exports.insertToArray = function(req, err, res) {   
    var title = req.body.title;
    var name = req.body.name;
    var comment = req.body.comment;
    var stars = req.body.stars;
    var date = req.body.date;
    Note.update(
        {title:title},
        {$push:{
            reviews:{
                $each:[
                    {
                        "name":name,
                        "comment":comment,
                        "stars":stars,
                        "date":date
                    }
                ]
            }
        }
        },function(err, results){
        console.log("Record added as ", results);
        res(results);
    });
};

我的数据模型如下:

  {
    "title": "Coffee Mug",
    "slogan": "Keep your coffee hot!",
    "description": "A mug is a type of cup used for drinking hot beverages, such as coffee, tea, hot chocolate or soup. Mugs usually have handles, and hold a larger amount of fluid than other types of cup. Usually a mug holds approximately 12 US fluid ounces (350 ml) of liquid; double a tea cup. A mug is a less formal style of drink container and is not usually used in formal place settings, where a teacup or coffee cup is preferred.",
    "stars": 0,
    "category": "Kitchen",
    "img_url": "/img/products/mug.jpg",
    "price": 12.5,
    "reviews": [
      {
        "name": "",
        "comment": "",
        "stars": 5,
        "date": 1456067725049
      },{
        "name": "",
        "comment": "",
        "stars": 5,
        "date": 1456067725059
      }
    ]
  }

和邮递员请求

{
    "title": "Coffee Mug",
    "name": "this is slogan2",
    "comment": "This is description",
    "stars": 3.4,
    "date": 220
}

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    $each 如果传递数组则使用 因为这是 json ,所以不需要 $each

    {$push:{
                reviews:{
                            "name":name,
                            "comment":comment,
                            "stars":stars,
                            "date":date
                         }
            }
    

    【讨论】:

    • 非常感谢您的回复。但是会有一个评论数组,但我弄错了。如果可能,请再看一遍
    • 你在model中定义了吗(注)
    • RITESH ARORA 非常感谢您的帮助,终于成功了
    猜你喜欢
    • 2016-02-13
    • 2015-09-06
    • 2020-08-14
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 2018-02-03
    • 1970-01-01
    相关资源
    最近更新 更多