10 回复
这个地方错了,应该是:
{
"user":"...",
"time":{
...
},
"title":"...",
"post":"...",
"comments":[
{
"name":"lisi",
"email":"...",
"website":"...",
“time”:”...”,
"content":"..."
},
{
"name":"wangwu",
"email":"...",
"website":"...",
“time”:”...”,
"content":"..."
}
......
],
"_id":"..."
}
修复一个bug,在comment.js中我想先find那篇文章,获取id,然后通过id来update一个comment,这写错了:
query_id.id = doc._id;
最起码也应该是
query_id._id = doc._id;
。。。但我试了试貌似也不行,所我查了查node-mongodb-bative中正好有一个findAndModify。。它的作用就是find+update的合体,所以我们直接用这个findAndModify操作就可以了。 http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#findandmodify comment.js改成以下内容:
var mongodb = require('./db');
function Comment(user, day, title, comment) {
this.user = user;
this.day = day;
this.title = title;
this.comment = comment;
}
module.exports = Comment;
Comment.prototype.save = function(callback) {
var user = this.user,
day = this.day,
title = this.title,
comment = this.comment;
mongodb.open(function (err, db) {
if (err) {
return callback(err);
}
db.collection('posts', function (err, collection) {
if (err) {
mongodb.close();
return callback(err);
}
collection.findAndModify({"user":user,"time.day":day,"title":title}
, [['time',-1]]
, {$push:{"comments":comment}}
, {new: true}
, function (err,comment) {
mongodb.close();
callback(err,comment);
});
});
});
};