How to access a preexisting collection with Mongoose?

前端 未结 6 2091
终归单人心
终归单人心 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:18

    Something else that was not obvious, to me at least, was that the when using Mongoose's third parameter to avoid replacing the actual collection with a new one with the same name, the new Schema(...) is actually only a placeholder, and doesn't interfere with the exisitng schema so

    var User = mongoose.model('User', new Schema({ url: String, text: String, id: Number}, { collection : 'users' }));   // collection name;
    User.find({}, function(err, data) { console.log(err, data, data.length);});
    

    works fine and returns all fields - even if the actual (remote) Schema contains none of these fields. Mongoose will still want it as new Schema(...), and a variable almost certainly won't hack it.

提交回复
热议问题