gpt4 book ai didi

javascript - NodeJS - Mongoose ,subdoc 对象没有方法 .id() 或 .create()

转载 作者:搜寻专家 更新时间:2023-11-01 00:45:30 27 4
gpt4 key购买 nike

我正在尝试使用 .create() 插入子文档,并使用 .id() 查询所述文档。我一直在关注指南 here

我收到错误:对象没有方法“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();
});

}

无论哪种方式,他们都崩溃了,谷歌的答案非常渺茫。大多数人都提供了多种不同的方法来公开模式和模型,而我上面的内容几乎是他们建议的内容的总和。有任何想法吗?谢谢!

最佳答案

我一直在玩弄这个之后找到了答案。这很简单。声明架构的顺序很重要。所以我必须在声明我的父架构之前声明我的子文档架构。如:

var announcementsSchema= new Schema({
categoryName: String,
posts: [postSchema]
});

var postSchema = new Schema({
title: String,
dateCreated: String,
dateEdited: { type: Date, default: Date.now() },
summary: String,
body: String
});

这成功了!我现在能够保持所有其余代码不变,但现在方法存在了!

关于javascript - NodeJS - Mongoose ,subdoc 对象没有方法 .id() 或 .create(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19819346/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com