以下是我创建的所有模式。我使用方法findByIdAndUpdate()
向Club
架构添加新帖子。现在,我想在帖子中添加评论。我也尝试过同样的评论,但它没有用。我也试过this,我得到了下面提到的错误。任何帮助深表感谢。提前谢谢。
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Post = require('./posts');
var clubSchema = new Schema({
name: {
type: String,
required: true,
unique: true
},
abbreviation: {
type: String,
required: true,
unique: true
},
followers: {
type: Number,
default: 0
},
posts: [Post.Schema]
});
module.exports = mongoose.model('Club', clubSchema);
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Comment = require('./comments');
var postSchema = new Schema({
title: {
type: String,
required: true
},
content: {
type: String,
required: true
},
createdBy: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
},
comments: [Comment.Schema],
votes: {
type: Number,
default: 0
}
});
module.exports = mongoose.model('Post', postSchema);
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var commentSchema = new Schema({
head: {
type: String,
required: true
},
content: {
type: String,
required: true
}
});
module.exports = mongoose.model('Comment', commentSchema);
我试过了。
app.post("/all_comments/:id", function(req, res) {
var new_comment = new Comment({
head: req.body.head,
content: req.body.content
});
Club.findById(req.params.id, function(err, club) {
var posts = club.posts;
// console.log(posts);
for(i in posts) {
if(posts[i]._id == req.body.id) {
console.log(posts[i]);
posts[i].comments.push(new_comment);
posts[i].save(function(err) {
if(err)
console.log(err);
});
club.save(function(err) {
if(err)
console.log(err);
else
res.send("Successful");
});
}
}
});
});
我得到的错误
TypeError: Object #<Object> has no method 'save'
答案 0 :(得分:0)
您不需要致电posts[i].save()
。
完成所有推送后,您只能拨打club.save()
一次。
答案 1 :(得分:0)
我没有深入研究这一点,但我确实注意到您正尝试使用Comment.Schema
访问模型的架构。根据Mongoose文档(http://mongoosejs.com/docs/api.html#model_Model-schema),属性应该是小写的,例如Comment.schema
。
尝试将每个记录到控制台,看看你得到了什么。