【问题标题】:update parent child data nodejs mongodb更新父子数据nodejs mongodb
【发布时间】:2015-11-25 17:33:30
【问题描述】:

我是 mongodb 的新手,使用 nodejs。我想更新 cmets 数据。这是我的文档

 {
       "__v": NumberInt(0),
       "_id": ObjectId("565443b1172e19d51f98b0ed"),
       "address": "tohana",
       "comments": [
         {
           "_id": ObjectId("5654455fe088d89c20736e3c"),
           "comment": "good man",
           "uemail": "dinesh@gmail.com",
           "uname": "dinesh" 
        },
         {
           "_id": ObjectId("565445e471dce6ca20705a84"),
           "comment": "nice person",
           "uemail": "kr@gmail.com",
           "uname": "krishan" 
        },
         {
           "_id": ObjectId("5654460e7aa73bec2064060e"),
           "comment": "bad person",
           "uemail": "Rai",
           "uname": "Rahul" 
        } 
      ],
       "email": "nishantg@ocodewire.com"▼,
       "name": "Nishant" 
    }

我在前端使用 Angular js,在后端使用 nodeJs。这是我的代码:

app.post('/commentsSave/:id', function(req, res) {
var id = req.params.id; // userId
var input = JSON.parse(JSON.stringify(req.body)); //commentData
var commentId = input.id; //commentId
var name  = input.name;
var email = input.email;
var comment = input.comment
res.send({data:id,data2:input});

}) 

【问题讨论】:

  • 你能添加你的猫鼬模型吗?你的意思是你只想更新现有文件中的 cmets?
  • 我已经添加了猫鼬模型。我只想更新评论..@prasun
  • 你想用mongoose还是mongodb原生驱动?

标签: node.js mongodb mongoose


【解决方案1】:
app.post('/commentsSave/:id', function(req, res) {
        var id = req.params.id; // userId
        var input = JSON.parse(JSON.stringify(req.body)); //commentData
        var commentId = input.id; //commentId
        var name  = input.name;
        var email = input.email;
        var comment = input.comment
        Users.update({'comments._id': input.id}, 
        {
            $set: {
                'comments.$.name': name,
                'comments.$.email': email,
                'comments.$.comment': comment
                }
        },function(error, result){
          if(error){
            console.log(error);
          }
          else{
           console.log(result);
          }
     })
}

【讨论】:

    猜你喜欢
    • 2016-02-27
    • 1970-01-01
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    相关资源
    最近更新 更多