在参数中使用ref作为参数的字段不起作用

时间:2018-03-24 13:28:57

标签: node.js mongodb mongoose

我有两个架构:

const BookSchema = new Schema({
    name: { type: String, required: true },
    author: [{ type: String }],
    category: [{ type: String }],
    store: { type:mongoose.Schema.Types.ObjectId, ref: 'Store'}
  });

module.exports = mongoose.model('Book', BookSchema);



const storeSchema = new Schema({
  name: { type: String, required: true },
  slug: { type: String, index: true, required: true, unique: true}
});

module.exports = mongoose.model('Store', StoreSchema);

我试图从商店获取图书,描述如下:

exports.getBooksFromStore = async(idStore) => {
  const data = await Book.find({store : idStore});

 return data;
} 

但是,以这种方式编写的find()并不起作用。

1 个答案:

答案 0 :(得分:0)

问题似乎是find方法在实际返回查询对象时返回promise对象的期望。在提供的示例代码中,分配给data的值是从find方法返回的查询对象,而不是执行查询时预期的promise对象。

要执行查询并为其返回promise对象,需要调用查询exec方法。

exports.getBooksFromStore = async (idStore) => {
  // const data = await Book.find({store : idStore});
  const data = await Book.find({store : idStore}).exec();

  return data;
};