【问题标题】:Mongoose: How to findById when the query is not completeMongoose:查询未完成时如何findById
【发布时间】: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


【解决方案1】:

您可以使用正则表达式运行查询,即使用 RegExp 构造函数从字符串创建正则表达式对象,然后运行查询:

ordersRouter.route('/searchorder/:term')
    .get(function(req, res){
        term = req.params.term;
        console.log(term);

        Orders.find({'orderId': new RegExp(term)})
            .populate({ 
                path: 'userPurchased products.product', 
                select: '-username -password' 
            })
            .exec(function(err, orders){
                if (err) throw err;

                res.json(orders);
            });
    });

【讨论】:

  • 这可以返回一个对象数组吗?我读到如果我使用正则表达式,它只会返回一项。
  • 是的,find().exe() 将返回一个数组,不,正则表达式只会返回与给定模式匹配的文档,例如如果您的orders 集合中有以下文档[ { orderId: 'test1' }, { orderId: 'test2' }, { orderId: 'test3' } ],则查询Orders.find({'orderId': new RegExp('test')}) 将返回所有文档,因为正则表达式/test/ 匹配这三个文档。
  • 请问搜索查询是否被删除,term 上没有值,如何再次显示所有项目?
猜你喜欢
  • 1970-01-01
  • 2018-09-16
  • 2018-06-11
  • 2018-11-09
  • 1970-01-01
  • 2013-01-08
相关资源
最近更新 更多