Mongoose查询比较ObjectId

时间:2018-04-08 16:05:40

标签: node.js mongodb mongoose

我正在尝试从我的数据库中获取一些文档。在每个文档中,都有一个名为“owner”的字段,它是用户的ObjectId。我想获取特定用户的所有文档。我有用户ID,当我尝试做这样的事情时:

exports.getBoxes = function(req, res) {
    const { user } = res.locals;
    const query = db.Box.find();
    query.where('owner').equals(user._id);
    query.exec(function(err, boxes) {
        console.log(boxes);
    });
}

我得到一个空数组。我在我的数据库中看到,有许多框对应于此查询。怎么了?

更新 这是我的架构:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const timestamps = require('mongoose-timestamps');

const BoxSchema = new Schema({
  description: {
    type: String,
    trim: true
  },
  producer: {
    type: String,
    trim: true
  },
  cycle: {
    type: String,
    trim: true
  },
  owner: {
    type: Schema.ObjectId,
    ref: 'Supplier'
  },
  event: {
    type: Schema.ObjectId,
    ref: 'Event'
  },
  type: {
    type: String,
    enum: []
  },
  creditTerms: {
    type: String,
    enum: ['Cash', '30 Days', '60 Days', '90 Days', '120 Days']
  },
  bids: [{
    type: Schema.ObjectId,
    ref: 'Bid'
  }],
  looking: [{
    type: Schema.ObjectId,
    ref: 'User'
  }],
  sold: Boolean,
  paid: Boolean,
  delivered: Boolean,
  sealed: Boolean,
  initialPrice: Number,
  value: Number,
  cts: Number,
  ppc: Number,
  finalPrice: Number
});

BoxSchema.plugin(timestamps);

module.exports = mongoose.model('Box', BoxSchema);

以下是我尝试获取的文档示例: https://i.gyazo.com/38f2d16d6831b831adb3cc448ef74d01.png

1 个答案:

答案 0 :(得分:1)

好的,我设法解决了这个问题。问题是框​​架构中的所有者字段引用了Supplier对象,而不是User对象。所以我解决了这个问题:

const { user } = res.locals;
return db.Supplier.findOne({ userId: user._id })
       .populate('boxes').exec(function(err, supplier) {
            if(err || !supplier) return res.sendStatus(404);

            res.json(supplier.boxes);
        });