I am using express js with mongoose and saving data into users collection but i want to know how can i change collection name ? Here is my code
app.post('/signup', (req, res, next) =>
{
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/cuts');
var User = require('./testing.js');
var newUser = new User();
newUser.name = req.body.name;
newUser.email = req.body.email;
newUser.save((err, User) => {
if (err) {
console.log(err);
}
else {
console.log("Signup Successfully");
}
});
});
Here is my testing.js
var mongoose = require('mongoose');
var UserSchema = mongoose.Schema({
name : {
type : String,
required : true
},
email : {
type : String,
required : true,
unique: true
}
});
const User = module.exports = mongoose.model('User', UserSchema);
Collection name is fetched from Model itself. Please changing model name.
Change this
const User = module.exports = mongoose.model('User', UserSchema);
to
const User = module.exports = mongoose.model('NewUser', UserSchema);
If you are trying to renaming the existing User collection, use
const mongoose = require('mongoose');
mongoose.Promise = Promise;
mongoose.connect('mongodb://localhost/cuts').then(() => {
let db = mongoose.connection.db;
return db.collection('User').rename('NewUserColl');
}).then(() => {
console.log('rename successful');
}).catch(e => {
console.log('rename failed:', e.message);
}).then(() => {
console.log('disconnecting');
mongoose.disconnect();
});
Go To your model and change your schemaname
const User = module.exports = mongoose.model('User', UserSchema);
To
const User = module.exports = mongoose.model('NewUser', UserSchema);
Mongo Db by Defaults take plural name of your schema name.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.