猫鼬-如何通过subDocument参数查找One?

时间:2019-07-18 14:19:47

标签: node.js mongoose

我尝试将findOne查询与sub-subDocument的属性作为条件,但不能正常工作。

所以之后,我在findOne查询之前自动填充了storie和国家/地区,但这还是行不通的...

你有什么想法吗?

谢谢, 文森特

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

const personSchema = Schema({
  _id: Schema.Types.ObjectId,
  name: String,
  age: Number,
  storie: { type: Schema.Types.ObjectId, ref: 'Story' }
});

/* Try after */
personSchema.pre('findOne', function(next) {
  this.populate({path: 'storie', populate:{path: 'country'}});
  next();
});


const storySchema = Schema({
  title: String,
  country: { type: Schema.Types.ObjectId, ref: 'Country' }
});

const countrySchema = Schema({
  name: String,
  lat: Number,
  long: Number
});

const Country = mongoose.model('Country', countrySchema);
const Story = mongoose.model('Story', storySchema);
const Person = mongoose.model('Person', personSchema);



Person.findOne({'storie.country.name': 'USA', age: 24}).exec( (err, person) => {
    if(!err) {
           console.log(person);
       }
});

0 个答案:

没有答案