Error in Mongoose findOne

Asked

Viewed 470 times

0

I’m getting Error: Invalid argument to findOne(): 'texto pesquisado' when executing the findOne mongoose:

const User = mongoose.model('users', mySchema);
const query - 'texto pesquisado';

User.findOne(query, function(err, data) {
    if (err) return console.log('ERROR: ', err);
    return console.log('DATA: ', data);
});

I am not finding the reason for this error, because the arguments of the function are apparently correct. Does anyone know what may be happening?

1 answer

0


findOne expects a document/object as parameter, not only a String as you passed it. Check in the example below:

const User = mongoose.model('users', mySchema);
const query = 'texto pesquisado';

User.findOne({nomecoluna: query}, function(err, data) {
    if (err) return console.log('ERROR: ', err);
    return console.log('DATA: ', data);
});

You can find more examples in the Mongoose documentation mongoosejs.with

  • I don’t understand what the relation of your response to the error I’m getting...

  • Error: Invalid argument to findOne(): 'searched text' when running Mongoose findOne: You’re just passing the value you want to search for in the document const query - 'searched text'; which is still wrong const query = 'searched text'; that’s right Here too you made a mistake User.findOne(query, Function(err, data) {} you only passed as argument a const query without giving the name of the column to fetch information from const query The right one would be User.findOne({column name: query}, Function(err, data) {} ({column name: query} and so you pass argument ! .

  • ah yes... now I realized my mistake. I picked up a code snippet with find() and only replaces by findOne() without realizing that in the findOne() is passed an object with nameField: value instead of just the string being searched. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.