【发布时间】:2017-06-27 09:24:18
【问题描述】:
我正在构建一个搜索查询,即使用户正在输入,它也会通过其 ID 查找数据库对象。
ordersRouter.route('/searchorder/:term')
.get(function(req, res){
term = req.params.term;
console.log(term);
Orders.findById(term)
.populate({ path: 'userPurchased products.product', select: '-username -password' })
.exec(function(err, orders){
if (err) throw err;
res.json([orders]);
});
});
这里的问题是,当term与ID不完全相同时,它不会返回任何内容。如何返回带有部分 term 的 ID?
编辑:我的订单模型架构
var orderSchema = new Schema({
orderId: { type: String },
userPurchased: { type: Schema.Types.ObjectId, ref: 'users' },
products: [
{
product: { type: Schema.Types.ObjectId, ref: 'products' },
size: { type: String, required: true },
quantity: { type: Number, required: true },
subTotal: { type: Number, required: true }
}
],
totalQuantity: { type: Number },
totalPrice: { type: Number },
modeOfPayment: { type: String },
shippingAd: { type: String },
refNumber: { type: String },
isDone: { type: Boolean, default: false },
orderStatus: { type: String, default: 'Pending' },
dateOrdered: { type: Date, default: Date.now() },
fromNow: { type: String }
});
【问题讨论】:
-
findById 期望 ID(ObjectID 的类型不是字符串、整数或其他任何东西)作为参数,那么您为什么还要尝试给它其他东西呢?我不认为你真的可以这样做。我能想到的最好方法是为每个订单提供 String 类型的自定义 id,然后您可以使用它仅通过部分 id 来查找。
-
所以当我将我的 ID 设为字符串时,即使它只是部分文本也可以使用 find?
-
我该怎么做?只是一个普通的查找查询?
-
我尝试使用类型字符串创建自定义 id 字段。使用通常的查找方法。不工作。
-
当然。我编辑了我的问题。我还添加了 orderId,其值与我的 _id 相同,但类型为字符串。
标签: node.js mongodb express mongoose