Sequelize could not create a new table - node.js

I'm currently learning sequelize and its define method is used to create new database table, but it is not working...there is no error...do you know whats going on?
var express = require('express');
var Sequelize = require('sequelize');
var sequelize = require('../db/sequelize_conf.js');
var router = express.Router();
var User = sequelize.define('user',
{
name: Sequelize.STRING,
password: Sequelize.STRING,
mail: Sequelize.STRING
},
{
freezeTableName: true,
timestamps: false
});
User.create({
name: 'XiaoMing',
password: '1234567890',
mail: 'xiaoming#qq.com'
}).then(function(result){
console.log('inserted XiaoMing ok');
}).catch(function(err){
console.log('inserted XiaoMing error');
console.log(err.message);
});
module.exports=router;
It says the user table doesnt exist....

Okay ,
First check in the database if user table is there or not , coz the below code won't create a new table , it will just create a new entry in to user table
User.create({
name: 'XiaoMing',
password: '1234567890',
mail: 'xiaoming#qq.com'
})
If you want to create a table then you can use ,
// This will create only all the tables defines via sequelize
sequelize.sync().then(() =>
// put your user create code inside this
);
// OR
// This will create only user table
User.sync().then(() => {
// put your user create code inside this
});
I hope this will clear all your doubts

Related

Mongoose: OverwriteModelError: Cannot overwrite `users` model once compiled

I'm using Mongoose to manage a MongoDB server, and all other solutions with this error have not helped. The models aren't defined anywhere else, and the only issue I can think of is that the tables/models already exist on the MongoDB server, but other than that I've never had this issue before.
My current code is this:
const mongoose = require('mongoose');
mongoose.connect(process.env.DATABASE_URL, {useNewUrlParser: true, useUnifiedTopology:true});
const users = require('../../models/Users.schema')
const accounts = require('../../models/Account.schema')
export default (req, res) => {
users.findOne({ email: req.body.email }, function (err, user) {
console.log(user)
accounts.findOne({ userId: user._id }, function (err, account) {
console.log(account)
return res.json({
error: false,
body: account
})
})
})
}
Users schema (mainly for an example, this issue happens with all schemas)
const mongoose = require('mongoose');
const usersSchema = new mongoose.Schema({
name: String,
email: String,
image: String,
createdAt: Date,
updatedAt: Date
})
module.exports.users = mongoose.model('users', usersSchema);
What I'm trying to do is get the data from NextAuth that isn't provided normally, such as the accessToken (session.accessToken is not the right accessToken).
I'm not sure what to do, and I'll take any help I can get.
Thanks!
The error is occurring because you already have a schema defined, and then you are defining the schema again

Sequelize - Custom Create Method

Is it possible to create a custom create method in Sequelize. I would like it so that I could pass in a URL to download a thumbnail photo from, and then a method would be called with that data to download the photo, upload it to S3, and save that S3 URL as the thumbnailPhotoURL.
Here is an example of the syntax I'm trying to do:
var Sequelize = require('sequelize');
var sequelize = new Sequelize('database', 'username', 'password');
var User = sequelize.define('user', {
username: Sequelize.STRING,
birthday: Sequelize.DATE,
thumbnailPhotoURL: Sequelize.STRING
});
sequelize.sync().then(function() {
return User.create({
username: 'janedoe',
birthday: new Date(1980, 6, 20),
// this will be used to download and upload the thumbnailPhoto to S3
urlToDownloadThumbnailPhotoFrom: 'http://example.com/test.png'
});
}).then(function(jane) {
console.log(jane.get({
plain: true
}));
});
Notice how I'm calling User.create with a urlToDownloadThumbnailPhotoFrom parameter, rather than a thumbnailPhotoURL parameter
You can use before create hook no need to define a custom create function
var Sequelize = require('sequelize');
var sequelize = new Sequelize('database', 'username', 'password');
var User = sequelize.define('user', {
username: Sequelize.STRING,
birthday: Sequelize.DATE,
thumbnailPhotoURL: Sequelize.STRING
});
User.beforeCreate(function(model, options, cb) {
var urlToDownloadThumbnailPhotoFrom = model.urlToDownloadThumbnailPhotoFrom;
//.....Here you write the logic to get s3 url using urlToDownloadThumbnailPhotoFrom and then assign it to model and call the call back it will automatically get saved
model.thumbnailPhotoURL = thumbnailPhotoURL;
cb();
});

Mongoose - inserting subdocuments

I have a user model, and a log model. The log model is a subdocument of user model. So in my user model I have:
var mongoose = require('mongoose');
var Log = require('../models/log');
var UserSchema = new mongoose.Schema({
username: {
type: String,
unique: true
},
logsHeld: [
Log
]
});
Then in my 'Log' model I have:
var mongoose = require('mongoose');
var logSchema = new mongoose.Schema({
logComment: {
type: String,
},
});
module.exports = mongoose.model('Log', logSchema);
So upon creation of a 'user', the 'logsHeld' always begins empty. I want to know how to add subdocuments to this user model.
I've tried doing this POST method:
router.post('/createNewLog', function(req, res) {
var user = new User ({
logssHeld: [{
logComment: req.body.logComment
}]
});
user.save(function(err) {
if(err) {
req.flash('error', 'Log was not added due to error');
return res.redirect('/home');
} else {
req.flash('success', 'Log was successfully added!');
return res.redirect('/home');
}
});
});
But this doesn't work. It also includes a 'new User' line, which I don't think I need given this would be for an existing user.
You need to use the logSchema instead of the Log model as your subdocument schema in User model. You can access the schema as follows:
var mongoose = require('mongoose');
/* access the Log schema via its Model.schema property */
var LogSchema = require('../models/log').schema; // <-- access the schema with this
var UserSchema = new mongoose.Schema({
username: {
type: String,
unique: true
},
logsHeld: [LogSchema]
});
Picking up from your comments in another answer where you are facing another issue
WriteError({"code":11000,"index":0,"errmsg":"E11000 duplicate key
error index: testDB.users.$email_1 dup key:
you are getting this because there's already a document in your users collection that has most probably a null value on the email field. Even though your schema does not explicitly specify an email field, you may have an existing old and unused unique index on users.email.
You can confirm this with
testDB.users.getIndexes()
If that is the case and manually remove the unwanted index with
testDB.users.dropIndex(<index_name_as_specified_above>)
and carry on with the POST to see if that has rectified the error, I bet my $0.02 that there is an old unused unique index in your users collection which is the main issue.
Try using logSchema which references only the subdocument schema, Log refers to the entire contents of ../models/log
var UserSchema = new mongoose.Schema({
username: {
type: String,
unique: true
},
logsHeld: [
logSchema
]
});
Documentation: http://mongoosejs.com/docs/subdocs.html
Try push to insert item in array in mongoose
var user = new User;
user.logssHeld.push({
logComment: req.body.logComment
});
user.save(function(err, doc) {
//DO whatever you want
});
see the docs here

Node js and Code First

I've worked on Entity Framework with Code First approach. Now I am learning Node.js I wonder is there a way to make the same code first approach using Node.js and some libraly? I am thinking of using MySql as database.
You can look into Sequelize. Example of usage from the home page (I added comments to relate to Code First):
var Sequelize = require('sequelize');
// define your "context"
var sequelize = new Sequelize('database', 'username', 'password');
// define your "entities"
var User = sequelize.define('user', {
username: Sequelize.STRING,
birthday: Sequelize.DATE
});
// use them
sequelize.sync().then(function() {
return User.create({
username: 'janedoe',
birthday: new Date(1980, 6, 20)
});
}).then(function(jane) {
console.log(jane.get({
plain: true
}));
});

Save mongoose document again after deleting it

I try to unit test my restify node.js-app using mocha and without mocking out the mongodb database. As some tests will alter the database, I'd like to reset its contents before each test.
In my tests I also need to access the mongoose documents I am creating. Thus I have to define them outside of the beforeEach hook (see the user document below).
However, it seems like it's not possible to save a document a second time after emptying the database.
Below is a minimal example I've come up with. The second test will fail in that case, because user won't get saved a second time. If I delete the first test, beforeEach only gets called once and everything works nicely.
Also if I define user inside the beforeEach hook, it works as well.
So my actual question: Is it possible to work around this issue and save a document a second time after deleting it? Or do you have any other idea on how I can reset the database inside the beforeEach hook? What's the proper way to have the same database setup before each test case?
var mongoose = require('mongoose')
var Schema = mongoose.Schema
var should = require('should')
var flow = require('async')
var UserSchema = new Schema({
username: {type: String, required: true, unique: true},
password: {type: String, required: true},
name: {type: String, default: ''}
})
mongoose.model('User', UserSchema)
var User = mongoose.model('User')
describe('test mocha', function() {
var user = new User({
username: 'max',
password: 'asdf'
})
before(function(done) {
var options = {server: {socketOptions: {keepAlive: 1}}}
mongoose.connect('mongodb://localhost/unittest', options, done)
})
beforeEach(function(done) {
flow.series([
function(callback) {
User.collection.remove(callback)
}, function(callback) {
user.save(callback)
}
], function(err, res) {
done()
})
})
it('should pass', function(done) {
true.should.equal(true)
// also access some elements of user here
done()
})
it('should have a user', function(done) {
User.find().exec(function(err, res) {
res.should.not.be.empty
})
done()
})
after(function(done) {
mongoose.disconnect()
done()
})
})
I faced same problem,I generated a copy of the document to save. When need to save the document after deleting it I saved the copy, and it worked. Like
var user = new User({
username: 'max',
password: 'asdf'
});
var userCopy = new User({
username: 'max',
password: 'asdf'
});
And in test cases.
user.remove(callback)
}, function(callback) {
userCopy.save(callback){
// should.not.exist(err)
}
}
It might not be good solution ,but it worked for me.

Resources