I have username and password for mongoose, i used this url to connect the mongodb using mongoose
I try this one :
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://adminuser:123456@localhost:2017/mydb');
mongoose schema is
// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a schema
var userSchema = new Schema({
name: String,
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
admin: Boolean,
location: String,
meta: {
age: Number,
website: String
},
created_at: Date,
updated_at: Date
});
// the schema is useless so far
// we need to create a model using it
var User = mongoose.model('User', userSchema);
// make this available to our users in our Node applications
module.exports = User;
and my controller is
router.post('/signup',function(req,res){
console.log("Inside")
var useR= new User({
name: 'Chris',
username: 'sevilayha',
password: 'password'
});
useR.save(function(err) {
if (err) throw err;
console.log('User saved successfully!');
});
});
but its not stored in database .
First check whether it connected or node using on event.
mongoose.connect('mongodb://adminuser:123456@localhost:2017/mydb');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
console.log("h");
});
exports.test = function(req,res) {
console.log(res)
};
Few years later, updating the new connect code here with additional options -
mongoose.connect(
'mongodb://user:pass@myhost:27017/my-db?authSource=admin',
{
useNewUrlParser: true,
useUnifiedTopology: true,
},
(err) => {
if (err) {
console.error('FAILED TO CONNECT TO MONGODB');
console.error(err);
} else {
console.log('CONNECTED TO MONGODB');
app.listen(80);
}
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With