我是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
});
请帮忙
答案 0 :(得分:0)
/**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);
}
})
答案 1 :(得分:-1)
测试一下:
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){});