简体   繁体   English

NodeJS-猫鼬,子文档对象没有方法.id()或.create()

[英]NodeJS - Mongoose, subdoc object has no method .id() or .create()

I am trying to insert a subdocument using .create() and also query said document using .id(). 我正在尝试使用.create()插入一个子文档,并且还使用.id()查询该文档。 I've been following the guide here 我一直在这里遵循指南

I am getting the error: object has no method 'id()' or 'create()' 我收到错误消息:对象没有方法'id()'或'create()'

The following is my code: 以下是我的代码:

/db/schemas/AnnouncementsSchema.js /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 /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});
        });
    });

}

I have the .save method wrapped so I can add extra functionality if needed. 我包装了.save方法,因此可以根据需要添加其他功能。 I crashes when it calls .create(). 当它调用.create()时,我崩溃了。 The same is true if I am trying to remove a post as well. 如果我也要删除帖子,也是如此。 Here is the code for that: 这是该代码:

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();
    });

}

Either way they both crash and google is pretty slim on answers. 无论哪种方式,它们都崩溃了,谷歌的答案也很渺茫。 Most people have given a of different ways to expose the schemas and models, and what I have above is pretty much a sum of what they suggested. 大多数人都给出了公开架构和模型的不同方法,而我上面所说的几乎是他们建议的总和。 Any ideas? 有任何想法吗? Thanks! 谢谢!

I found the answer after toying with this forever. 我一直在玩弄之后找到了答案。 It was simple. 很简单。 The order in which you declare your schema matters. 声明架构的顺序很重要。 So I had to declare my subdocument schema before I declare my parent schema. 因此,在声明父架构之前,必须先声明子文档架构。 Such as: 如:

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
});

This worked! 这工作了! I am now able to keep all the rest of the code the same, but now the methods exist! 现在,我可以将其余所有代码保持不变,但是现在方法就存在了!

Even if I recently picked up Express.js, I will do my best in trying to provide a useful answer. 即使我最近选择了Express.js,我也会尽力提供有用的答案。 Hope it helps! 希望能帮助到你!

If you want to access the id of a particular post, it is stored in the ._id property, not id . 如果要访问特定帖子的ID,它将存储在._id属性中,而不是id Moreover, I believe that you first have to loop over object.posts since it is an array of posts: 而且,我相信您首先必须遍历object.posts因为它是一系列的帖子:

exports.DeletePost = function (req, res) {

    var announcements = announcementsSchema.announcements;

    var announcementId = req.body.announcementId;
    var postId = req.body.postId; // This is the _id property of an element contained within the posts array
    var postToDelete = {};

    announcements.findById(announcementId, function (err, object) {

        // Get the posts array
        var posts = object.posts;

        // Loop over it until you find the post with the id that you stored in postId
        for (var i = 0; i < posts.length; i ++) {
           if (posts[i]._id == postId) {
               postToDelete = posts[i];
           }
        }

        console.log(postToDelete);

        res.end();
    });

}

As for your InsertPost function, you should also take into account the fact that posts is an array. 至于您的InsertPost函数,您还应该考虑posts是数组的事实。 Hence, you could simply push the new post into that array and save it accordingly: 因此,您可以简单地push新帖子push送到该数组中并进行相应保存:

exports.InsertPost = function (req, res) {

    var announcements = announcementsSchema.announcements;
    var post =  announcementsSchema.post;

    var announcementId = req.body.announcementId; 

    var newPost = req.body.newPost;

    announcements.findById(announcementId, function (err, announcment) {

        var postToAdd = new post(newPost);

        announcment.posts.push(postToAdd);

        announcment.save(function(err) {
           if (err) {
               res.send(500, { error: err.stack });
           }

           console.log('Success');

           res.end();
        });
    });

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM