return FALSE; $r = well_tag_thread__update(array('id' => $id), $update); return $r; } function well_tag_thread_find($tagid, $page, $pagesize) { $arr = well_tag_thread__find(array('tagid' => $tagid), array('id' => -1), $page, $pagesize); return $arr; } function well_tag_thread_find_by_tid($tid, $page, $pagesize) { $arr = well_tag_thread__find(array('tid' => $tid), array(), $page, $pagesize); return $arr; } ?>javascript - How to make a search api in nodejs and mongodb - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to make a search api in nodejs and mongodb - Stack Overflow

programmeradmin2浏览0评论

I am trying to make a search api using nodejs and MongoDB. I tried to google about this and I did find something there but while trying to implement I get an error saying. I don't know how to fix this honestly I don't know anything about making search API. So any help or suggestion will be helpful for me.

This is the link of the post I found on google Building a simple search api.

error

{
    "error": {
        "message": "Cast to ObjectId failed for value \"search\" at path \"_id\" for model \"Post\"",
        "name": "CastError",
        "stringValue": "\"search\"",
        "kind": "ObjectId",
        "value": "search",
        "path": "_id"
    }
}

This is my code

postController.search = (req, res) => {
    var response = [];
    if(typeof req.query.title !== 'undefined'){
        db.Post.filter(function(post) {
            if(post.title === req.query.title){
                console.log(req.body);
                response.push(post);
                console.log(post);
            }
        });
    }
    response = _.uniqBy(response, '_id');
    if(Object.key(req.query).length === 0){
        response = db.Post
    }
    res.json(response);
};

data in the collection

"data": [
    {
        "isDeleted": false,
        "_ments": [],
        "_id": "5d39122036117d2ea81b434c",
        "title": "facebook  post",
        "link": "facebook",
        "_creator": {
            "createdAt": "2019-07-25T01:42:21.252Z",
            "username": "adityakmr"
        },
        "createdAt": "2019-07-25T02:21:20.634Z",
        "__v": 0
    },
]

I am trying to make a search api using nodejs and MongoDB. I tried to google about this and I did find something there but while trying to implement I get an error saying. I don't know how to fix this honestly I don't know anything about making search API. So any help or suggestion will be helpful for me.

This is the link of the post I found on google Building a simple search api.

error

{
    "error": {
        "message": "Cast to ObjectId failed for value \"search\" at path \"_id\" for model \"Post\"",
        "name": "CastError",
        "stringValue": "\"search\"",
        "kind": "ObjectId",
        "value": "search",
        "path": "_id"
    }
}

This is my code

postController.search = (req, res) => {
    var response = [];
    if(typeof req.query.title !== 'undefined'){
        db.Post.filter(function(post) {
            if(post.title === req.query.title){
                console.log(req.body);
                response.push(post);
                console.log(post);
            }
        });
    }
    response = _.uniqBy(response, '_id');
    if(Object.key(req.query).length === 0){
        response = db.Post
    }
    res.json(response);
};

data in the collection

"data": [
    {
        "isDeleted": false,
        "_ments": [],
        "_id": "5d39122036117d2ea81b434c",
        "title": "facebook  post",
        "link": "facebook.",
        "_creator": {
            "createdAt": "2019-07-25T01:42:21.252Z",
            "username": "adityakmr"
        },
        "createdAt": "2019-07-25T02:21:20.634Z",
        "__v": 0
    },
]
Share Improve this question edited Jul 25, 2019 at 5:27 aditya kumar asked Jul 25, 2019 at 5:19 aditya kumaraditya kumar 3,02311 gold badges44 silver badges90 bronze badges 6
  • Please share your one sample collection data. – IftekharDani Commented Jul 25, 2019 at 5:25
  • Look like this(jonathanmh./…) provide search on JSON not for mongo. – IftekharDani Commented Jul 25, 2019 at 5:26
  • you can directly apply query on Mongo for search – IftekharDani Commented Jul 25, 2019 at 5:27
  • I have added sample data to my question have a look. – aditya kumar Commented Jul 25, 2019 at 5:28
  • yes post uses JSON data I though same way can be used for MongoDB as well that's why I tried and I could not find any other tutorial. – aditya kumar Commented Jul 25, 2019 at 5:29
 |  Show 1 more ment

3 Answers 3

Reset to default 1

If you're trying to create an API to search mongoDB collection based on title i.e; a text field try implementing text search feature of mongoDB : text search in mongoDB , Just create a text index on title field & then create an API with post method which takes in parameter that can be queried against title field.

Text search can be a bit tricky it can help you for fuzzy/partial/full text searches - use of regex is also much beneficial.

Checkout links for node.js API example :

MongoDB NodeJs Docs

Full Text Search with MongoDB & Node.js

Text Searching with MongoDB

First of all, you need to use async/await for modularize your code. I suggest don't write your whole code in your controller.js file, API can be made by following the way (routes - controller - utils ).

postRoutes.js

 postRouter.get('/search-post', postCtr.searchPost);

postController.js

const postUtils = require('./postUtils');

const postController = {};

postController.searchPost = async (req, res) => {
  try {
    const { title } = req.query;
    const result = await postUtils.searchPost(title);
    return res.status(200).json(result);
  } catch (err) {
    return res.status(err.code).json({ error: err.error });
  }
};

module.exports = postController;

postUtils.js

const Post = require('./postModel');

const postUtils = {};

postUtils.searchPost = async (title) => {
  try {
    let result = [];
    if(title){
      // Even you can perform regex in your search 
      result = await Post.find({ title: title });
    }
     return result;
  } catch (err) {
    const errorObj = { code: 500, error: 'Internal server error' }; // It can be dynamic
    throw errorObj;
  }
};

module.exports = postUtils;

postModel.js

const mongoose = require('mongoose');

const postSchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'user',
    required: true,
  },
  // Your fields ...
}, { collection: 'post', timestamps: true });

const post = mongoose.model('post', postSchema);

module.exports = post;

Using this structure you can easily debug your code and It's also manageable.

In the link you specified above, they are using array of objects stored in file called store.js, but not mongoDB. So directly they are filtering using Array.filter method.

But in mongoDB using mongoose(object modeling tool) you can make use of collection.find() method.

So solution to your problem is as follows

postController.search = async (req, res) => {
    var response = [];
    if (req.query.title) {
         response = await db.Post.find({title: req.query.title});
    }
    res.json(response);
 };

find is inbuilt query method which helps in querying the collections, you can pass multiple properties for querying.

发布评论

评论列表(0)

  1. 暂无评论