How to associate a mongoose model with the right MongoDB collection in Express.js app?

依然范特西╮ 提交于 2021-02-08 04:11:46

问题


how to point to particular collection in mongodb using mongoose ORM in express js app .

NA

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var personSchema = new Schema({
 name: String,
 age: Number
});

module.exports = mongoose.model('person', personSchema);

consider my mongo database have multiple collection ,so how will my above code will point to particular collection.


回答1:


I'm really sorry my selected answer is not accurate. I can't delete it because it is accepted. The accurate answer to your question is, mongoose.model('person', personSchema); will automatically create a plural lower case version of the model name.In this case, it will automatically create a collection persons in mongoDB if it doesn't exist already. If you want to override this default behavior, you can do it like this:

var personSchema = new Schema({ name: String, age: Number }, { collection:'people' });

or

mongoose.model( 'person', personSchema, 'people' ) so you refer to it as person, but collection name will be people




回答2:


Usually we follow convention of naming the collection plural in mongoDB. For example in MongoDB, we create users table, but use singular in Node.js. So the exports would be:

module.exports = mongoose.model('users',UserSchema)

And in other script, we require it as follows: const User=require('<pathToModel>/user')

This means we are referring to the model as User, it is based on UserSchema and the collection associated with this is users

In your code, you could do this:

module.exports = mongoose.model('person', personSchema); 



回答3:


If you have a specific collection you want documents based on a specific model to go into, you can use mongoose.model('person', personSchema, collection).

Or, you could name the desired associated collection in the Schema definition:

var dataSchema = new Schema({..}, { collection: 'data' });

https://mongoosejs.com/docs/guide.html



来源:https://stackoverflow.com/questions/53910967/how-to-associate-a-mongoose-model-with-the-right-mongodb-collection-in-express-j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!