Pedro Papel
Pedro Papel

Reputation: 63

Having trouble using Mongoose's find(), what is the correct way to use it?

I'm currently learning MongoDB using mongoose and nodeJS. I'm trying to store notes to a database called 'notes'. For this, first I connected to the database like this:

mongoose.connect(`mongodb+srv://pedro_yanez:${password}@fsopen-2021-project.ngteq.mongodb.net/note-app?retryWrites=true&w=majority`,
{
    useNewUrlParser: true,
    useUnifiedTopology: true,
})

Then, I created a Note Schema and a Note Model:

const noteSchema = new mongoose.Schema({
    content: String,
    date: Date,
    important: Boolean
})

const Note = mongoose.model('Note', noteSchema)

Then, I saved three documents to the database:

 const note = new Note({
     content: 'Note #N',
     date: new Date(),
     important: true
 })

 note.save().then(result => {
     console.log('note saved!')
     mongoose.connection.close()
 })

This was successfull as I can see them on MongoDB Atlas' collections, but when I try to query the uploaded notes using mongoose's find() method the following way:

Note.find({}).then(result => {
result.forEach(note => {
        console.log(note)
    })
    mongoose.connection.close()
})

I get the following error:

node_modules/mongoose/lib/query.js:2151
    return cursor.toArray(cb);
                  ^

TypeError: cursor.toArray is not a function

Note that the code that I attached is from HY's 'Full Stack Open 2021' course, from part3.c.

I also tried to use find() with a callback function as stated here:

Note.find({}, function (err, docs) {console.log(docs)});
mongoose.connection.close()

But I get 'undefined' and another error:

/node_modules/mongodb/lib/collection.js:238
            throw new error_1.MongoInvalidArgumentError('Method "collection.find()" accepts at most two arguments');
                  ^

MongoInvalidArgumentError: Method "collection.find()" accepts at most two arguments

I could really use a hint on what's wrong with my implementation, as I've been fighting with this all day!

Upvotes: 1

Views: 506

Answers (1)

Thiago Vasques
Thiago Vasques

Reputation: 31

I see we are in the same exercise on Fullstack open. I managed to log all "notes" following the quick start from https://mongoosejs.com/

After mongoose.connect:

    const db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', function() {
        // Here I used the Model.find() at the end of the page and closed 
        // the connection as they say in the lesson.
    });

It worked here, hope it helps.

Upvotes: 3

Related Questions