Wilbeibi Wilbeibi - 3 months ago 28
Node.js Question

Mongoose: Generate Schema from existing data

For example, I have

user
collection in db:

{'_id':0, 'name': 'Joe', 'score':[80, 33]}
{'_id':1, 'name': 'Moe', 'score':[90, 81]}
... ...


How can I read this data with existing format, which means, use it's existing schema without create a new one.

I read Mongoose doc and googled for a while but didn't find satisfied answer.

Answer

It will work if you make a model with the same schema.

var schema = new mongoose.Schema({ name: 'string', score: [] });
var user = mongoose.model('User', schema);

Edit:

Mongoose is an ODM, so you need a schema to create objects. If you need to run queries and get raw data from the database, I would stick with this library:

https://github.com/mongodb/node-mongodb-native