0

I'm trying to make a search option by name in node.js and it will search local database, if it finds the name it will display in webpage. But I'm getting the error in this syntax : user.find({id : findname}, which I have used in below code.

router.get('/', function(req, res, next) {
var findname = req.body.findname;
 res.render('detail', { title: 'Detail' });
});
mongoose.connect('mongodb://localhost/student');
var testSchema = new mongoose.Schema({
id : Number,
name : String,
email : String,
age : Number,
college : String
});

var user = mongoose.model('stud', testSchema, 'stud');

router.post('/show', function(req, res){
  user.find({name : findname}, function(err, docs){
       res.render('detail',{users:docs});
  });

});

3
  • 1
    What is the problem, and what is the goal? What is the expected result, and what is the actual result? Why is findname declared after it is used? Commented May 21, 2015 at 10:49
  • Awesome of you to tell us ^^ But if you have a problem, please describe it, provide some logs, say what you wanted to achieve :) Commented May 21, 2015 at 10:52
  • I have edited the question and explained my problem. Commented May 21, 2015 at 11:10

2 Answers 2

1

So, the problem is you've defined your findname variable in one function and are trying to use it in another. In order to accomplish what you're looking for, your router.post function should probably look something like this:

router.post('/show', function(req, res){
  var findname = req.body.findname
  user.find({name : findname}, function(err, docs){
    res.render('detail',{users:docs});
  });
});

Make sure you're using the correct middleware to populate the req.body object as well, or the code still won't work.

Sign up to request clarification or add additional context in comments.

1 Comment

Problem was with syntax : user.find({name : req.body.findname}}, here name should be written like : "name"
0

I suggest you to read the mongoose documentation Mongoose Doc. The id (and _id) fields are automatically assigned by Mongoose. The id is a virtual getter on the _id, it is a string or hex representation of the _id. Try to change the name of your field ­id by myId.

Anyway, your id is of type number and your try to match it with findname which is I guess a string ? Is there a type mismatch here ?

1 Comment

No, thats not the problem I had changed it to name and still getting the same error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.