How to access a preexisting collection with Mongoose?

前端 未结 6 2075
终归单人心
终归单人心 2020-11-28 00:53

I have a large collection of 300 question objects in a database test. I can interact with this collection easily through MongoDB\'s interactive she

6条回答
  •  情深已故
    2020-11-28 01:32

    Here's an abstraction of Will Nathan's answer if anyone just wants an easy copy-paste add-in function:

    function find (name, query, cb) {
        mongoose.connection.db.collection(name, function (err, collection) {
           collection.find(query).toArray(cb);
       });
    }
    

    simply do find(collection_name, query, callback); to be given the result.

    for example, if I have a document { a : 1 } in a collection 'foo' and I want to list its properties, I do this:

    find('foo', {a : 1}, function (err, docs) {
                console.dir(docs);
            });
    //output: [ { _id: 4e22118fb83406f66a159da5, a: 1 } ]
    

提交回复
热议问题