Mongoose中间件删除 - 无法使用find

时间:2018-02-08 08:24:58

标签: node.js mongodb mongoose

我遇到猫鼬问题。 我有2个对象,部分和产品,以及我的章节包含对产品的引用。

因此,当我删除产品时,我想在我的部分删除对该产品的引用。 为此,在我的产品模型中,我使用schema.post(' remove',....) 但是当在里面使用Section.find()时,我得到一个错误。

有人有想法吗? 这是我的代码:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var Section = require('./section');

var schema = new Schema({
    name: {type: String, required: true, unique: true},
    picture: {type: String},
    description_preview: {type: String},
    description_detail: {type: String},
    benefits_detail: {type: String},
    position: {type: Number},
    sections: [{type: Schema.Types.ObjectId, ref: 'Section'}]
});



schema.post('remove', function (product) {
    product.sections.map ( sectionID => {
        console.log('sectionID dans remove :');
        console.log(sectionID);
        Section.findById(sectionID,  function (err, section) {
            console.log('found')
            if (err) {
                return res.status(500).json({
                    title: 'An error occurred',
                    error: err
                });
            }
            if (!section) {
                return res.status(500).json({
                    title: 'No Message Found!',
                    error: {message: 'Message not found'}
                });
            }
        })
    })
});

一切正常,直到Section.findById()

谢谢

1 个答案:

答案 0 :(得分:0)

尝试findOne instaed of findById like

   Section.findOne({"_id": sectionID},function (err, section) {
            console.log('found')
            if (err) {
                return res.status(500).json({
                    title: 'An error occurred',
                    error: err
                });
            }
            if (!section) {
                return res.status(500).json({
                    title: 'No Message Found!',
                    error: {message: 'Message not found'}
                });
            }
        })