【问题标题】:Mongodb Save data with nodejsMongodb用nodejs保存数据
【发布时间】:2016-02-26 17:59:13
【问题描述】:

我是 mongodb 的新手。我只是使用 mongodb 插入数据。我的文档看起来:

{

   "_id": ObjectId("5654085bf61deb761109d157"),
   "address": "dsaddsadsad",
   "email": "dsaddsadsad",
   "name": "sadasdasdsad",
   "__v": NumberInt(0) 
}

我的模型看起来:

// grab the mongoose module
var mongoose = require('mongoose');

// define our nerd model
// module.exports allows us to pass this to other files when it is called
module.exports = mongoose.model('users', {
    name : {type : String, default: ''},
    email : {type : String, default: ''},
    address : {type : String, default: ''},

});

现在有一个用户对此发表评论。那么文档应该是:

{
     "comments": [
     {
       "uname": "arpit",
       "uemail": "arpit@gmail.com",
       "comment": "How can Make we this at good",
       "posted_at": ISODate("2015-11-19T11:06:03.628Z") 
    },
     {
       "uname": "sumit",
       "uemail": "sumit@ggi.net",
       "comment": "this is also well for me",
       "posted_at": ISODate("2015-11-19T11:06:27.172Z") 
    } 
  ],
       "_id": ObjectId("5654085bf61deb761109d157"),
       "address": "dsaddsadsad",
       "email": "dsaddsadsad",
       "name": "sadasdasdsad",
       "__v": NumberInt(0) 
    }

我怎样才能制作这个文件。我的代码是:

var Users = require("../app/models/users");
app.post('/comments/:id', function(req, res) {
var id = req.params.id; //coment id
var input = JSON.parse(JSON.stringify(req.body)); //comment data
//code should be here
});

请帮忙

【问题讨论】:

  • 你在模型中定义了cmets吗?

标签: angularjs node.js mongodb mongoose


【解决方案1】:
/**users model*/
var mongoose = require('mongoose');
module.exports = mongoose.model('users', {
    name : {type : String, default: ''},
    email : {type : String, default: ''},
    address : {type : String, default: ''},
    comments: []
});

var Users = require("../app/models/users");
app.post('/comments/:id', function(req, res) {
   var id = req.params.id; //coment id
   var object = {}
   for(var key in req.body){
      object[key] = req.body[key];
    }
    Users
      .findByIdAndUpdate(req.params.id, {$push: {"comments": object}})
      .exec(function(error, result){
          if(error){
            console.log(error);
          }
          else{
           console.log(result);
          }
     })

【讨论】:

    【解决方案2】:

    测试一下:

    Users.findByIdAndUpdate(id, {$push: {"comments":{
         uname: req.body.the_uname,
         uemail : req.body.the_uemail,
         comment: req.body.the_comment,
         posted_at: Date.now() 
       } 
     }
    }).exec(function(error, res){});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-03
      • 1970-01-01
      • 2021-12-18
      • 2021-06-20
      • 1970-01-01
      • 2017-05-12
      • 2015-05-21
      • 1970-01-01
      相关资源
      最近更新 更多