使用Mongoose ORM创建搜索查询

时间:2019-10-02 13:26:27

标签: mongoose

我正在尝试使用Mongoose ORM创建搜索查询。搜索可以找到零件号,零件描述或NSN号。但是,我不知道用户要搜索的三个。我不确定如何最好地实施此解决方案,或者Mongoose甚至无法实现。

let mongoose = require('mongoose');
let mongooseUniqueValidator = require('mongoose-unique-validator');

// Global variables
let Schema = mongoose.Schema;

// Define part schema
let schema = new Schema({
    // _id: mongoose.Schema.Types.ObjectId,
    nsn: { type: String, trim: true, unique: true, minlength: 1 },
    partList: { type: String, trim: true },
    description: { type: String, trim: true },
    dataSheet: [{
        mrc: { type: String, trim: true },
        tipText: { type: String, trim: true },
        category: { type: String, trim: true },
        categoryDescription: { type: String, trim: true },
        url: { type: String, trim: true },
    }],
    category: { type: String, trim: true, minlength: 1 },
    subcategory: { type: String, trim: true, minlength: 1 },
    filter: { type: String, trim: true, minlength: 1 },
    url: { type: String, trim: true },
    createdAt: Date,
    updatedAt: Date
})

// plugin middleware
schema.plugin(mongooseUniqueValidator);

// create indexes
schema.index({nsn: 'text', partList: 'text', description: 'text'});

// Export schema
module.exports = mongoose.model('Part', schema); ```




``` let searchString = req.params.search

    Part.find({$text: {$search: searchString}})
        .then(part => {
            if (part.length > 0) {
                res.json({
                    confirmation: 'success',
                    part: part
                });
            } else {
                res.status(204)
                    .json({

                    })
            }
        })
        .catch(err => {
            res.status(500)
                .json({
                    confirmation: 'fail',
                    message: err.message
                });
        }) ```

0 个答案:

没有答案