Reputation: 145
I am trying to create an API for user authentication to access data from SQL Server, however most resources I have found are based on MongoDB, such as this one: Restful API design with Node.js
I followed the tutorial and can connect to SQL Server by replacing 'mongoose' with 'mssql'.
Now there is a part that I can't figure out how to change it to the equivalent code:
// User.js
var mongoose = require('mongoose');
var UserSchema = new mongoose.Schema({
name: String,
email: String,
password: String
});
mongoose.model('User', UserSchema);
module.exports = mongoose.model('User');
The code above is using mongoose, but for SQL Server there is nothing like mssql.model
to use.
How can I achieve the same thing using SQL Server?
Edit: This is the official docs from Mongoose: Mongoose Models I need to achieve the same thing using the mssql package: mssql package
Upvotes: 2
Views: 2371
Reputation: 907
So MongoDB and SQL Server are like a lot different from one another. In MongoDB, there are documents and not table inside the databases, that mongoose.model is actually to be able to create a model for your document.
While to achieve the same kind of result (Since two are totally different), you may create a table using the following code: I am also providing connection method so you can verify that too.
var mysql = require('mysql');
var con = mysql.createConnection({
host: 'YOUR HOST',
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "CREATE TABLE users(name VARCHAR(255), email VARCHAR(255), password VARCHAR(25)";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
});
This will be helpful, to your specific query, although I suggest you to study SQL-server Query Language first and understand How you can create a query on NodeJS.
Upvotes: 4