我正在尝试使用 .create() 插入子文档,并使用 .id() 查询所述文档。我一直在关注这里的指南
我收到错误消息:对象没有方法 'id()' 或 'create()'
以下是我的代码:
/db/schemas/AnnouncementsSchema.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var postSchema = new Schema({
title: String,
dateCreated: String,
dateEdited: { type: Date, default: Date.now() },
summary: String,
body: String
});
var announcementsSchema= new Schema({
categoryName: String,
posts: [postSchema]
});
announcementsSchema.methods.Update = function (callback) {
console.log('Updating object: ' + this);
this.save(function (err, object) {
callback(err, object);
});
}
var announcements = mongoose.model('announcements', announcementsSchema);
var post = mongoose.model('post', postSchema);
module.exports = {
announcements: announcements,
post: post
};
/routes/Announcements.js
var mongoose = require('mongoose');
var announcementsSchema = require('../../db/schemas/AnnouncementsSchema.js');
exports.InsertPost = function (req, res) {
var announcements = announcementsSchema.announcements;
var post = announcementsSchema.post;
var categoryToEdit = req.body.categoryToEdit;
var newPost = req.body.newPost;
announcements.GetById(categoryToEdit._id, function (err, announcment) {
var postToAdd = new post(newPost);
announcment.posts.create(postToAdd);
announcment.Update(function (err, object) {
res.send({ err: err, data: object});
});
});
}
我包装了 .save 方法,因此如果需要,我可以添加额外的功能。当它调用 .create() 时我崩溃了。如果我也尝试删除帖子,情况也是如此。这是代码:
exports.DeletePost = function (req, res) {
var announcements = announcementsSchema.announcements;
var categoryId = req.body.categoryId;
var postId = req.body.postId;
announcements.findById(categoryId, function (err, object) {
var postToDelete = object.posts.id(postId);
console.log(postToDelete);
res.end();
});
}
无论哪种方式,他们都崩溃了,谷歌的答案也很渺茫。大多数人已经给出了不同的方式来展示模式和模型,而我上面的内容几乎是他们建议的总和。有任何想法吗?谢谢!