Mongoose find找不到ObjectId

时间:2016-03-29 22:52:52

标签: javascript node.js mongodb mongoose mongoose-schema

我在许多其他型号中都有同样的东西,但是在这个不起作用的情况下,是否有人能看到错误?

订单架构:

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;
var OrderItem    = require('./orderitem');

var OrderSchema  = new Schema({
    _account: {type: Schema.Types.ObjectId, ref: 'Account', required: true},
    status: String,
    active: Boolean,
    comment: String,
    items: [{type: Schema.Types.ObjectId, ref: 'OrderItem'}]
}, { timestamps: true });

OrderSchema.pre('remove', function(next) {
    console.log('order ID:', this._id);
    OrderItem.remove({_order: this._id}, next);
});

module.exports = mongoose.model('Order', OrderSchema);

订单商品架构:

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

var OrderItem = new Schema({
    _item: {type: Schema.Types.ObjectId, ref: 'Item', required: '{PATH} is required!'},
    _account: {type: Schema.Types.ObjectId, ref: 'Account', required: '{PATH} is required!'},
    _order: {type: Schema.Types.ObjectId, ref: 'Order', required: '{PATH} is required!'},
    comment: String,
    quantity: {type: Number, required: '{PATH} is required!'}
}, { timestamps: true });

OrderItem.pre('validate', function (next) {
    var Item     = require('./item');
    var err;
    Item.findOne({_id: this._item, _account: this._account}, function (err, item) {
        if (err) next(err);

        if (!item) {
            err = new Error("Item does not exist");
            next(err);
        }
        next();
    });
});

module.exports = mongoose.model('OrderItem', OrderItem);

问题是,当我尝试删除订单时,中间件预删除发生,console.log显示正确的ID但删除没有找到任何东西(这是一个找到item.remove()之前没有结果以及)

OrderSchema.pre('remove', function(next) {
    console.log('order ID:', this._id);
    OrderItem.remove({_order: this._id}, next);
});

如果我发现没有任何过滤器,它会给我所有项目,包括具有特定订单的项目,但当我尝试使用订单ID进行过滤时(这是正确的,我已经检查过)它总是返回一个空数组。

THX

0 个答案:

没有答案