node.js - 在查找中以 ref 作为参数的字段不起作用

标签 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() 不起作用。

最佳答案

问题似乎是对 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;
};

关于node.js - 在查找中以 ref 作为参数的字段不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49465250/

相关文章:

json - Mongoose查询结果是只读的吗?

node.js - 创建文档时如何附加文件

javascript - 如何处理服务器( Node js)中表单的数据?

node.js - SQLite3 - 在一条语句中创建多个表

node.js - mongodb 尝试删除可能不存在的集合

node.js - MongoDB/Mongoose 更新整个子/嵌套文档

javascript - OUT 在命令行中总是为空,但在 SQL 客户端中却不是?

java - morphea 以及如何更新现有文档字段

mongodb - 带有自定义标签的Docker图像提取

node.js - 带有嵌套可选对象的 Mongoose 模式