我有这两个模式:
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/