【问题标题】:NodeJS - Mongoose, subdoc object has no method .id() or .create()NodeJS - Mongoose,subdoc 对象没有方法 .id() 或 .create()
【发布时间】:2013-11-06 18:00:07
【问题描述】:

我正在尝试使用 .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();
    });

}

无论哪种方式,他们都崩溃了,谷歌的答案也很渺茫。大多数人给出了不同的方式来展示模式和模型,我上面的内容几乎是他们建议的总和。有任何想法吗?谢谢!

【问题讨论】:

    标签: javascript node.js express mongoose


    【解决方案1】:

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

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

    这行得通!我现在能够保持所有其余代码相同,但现在方法存在!

    【讨论】:

    • 太棒了!我重构了我的代码,它破坏了一个真正核心的功能(使用 id()),但我不知道为什么。非常感谢:)
    • @CMPSoares 在父架构之前定义子文档架构。这对我有用。
    【解决方案2】:

    即使我最近接触了 Express.js,我也会尽我所能提供有用的答案。希望对您有所帮助!

    如果您想访问特定帖子的 id,它存储在 ._id 属性中,而不是 id。此外,我认为您首先必须遍历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();
        });
    
    }
    

    至于您的 InsertPost 函数,您还应该考虑到 posts 是一个数组这一事实。因此,您可以简单地将新帖子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();
            });
        });
    
    }
    

    【讨论】:

    • 感谢您的回复,但 .id 和 .create 是通过 id 查找子文档的特殊方法。见here。它允许您查询而无需循环。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    • 2014-12-17
    • 1970-01-01
    • 2014-12-27
    • 2021-10-06
    相关资源
    最近更新 更多