I want add in auto increment for my model class in mean stack. How I do bellow class?
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/sampleApp');
module.exports = mongoose.model('User', {
email : { type: String, required: true, index: { unique: true } },
password : { type: String}
});
Related
I am confused about uuidv1(). In the following code it uses uuidv1() as a salt and encrypt a password. But I thought that uuidv1() generates different strings so that I am not able to use it to encrypting a password.
Does uuidv1() generate always the same strings?
const mongoose = require("mongoose");
const uuidv1 = require("uuid/v1");
const crypto = require("crypto");
const { ObjectId } = mongoose.Schema;
const userSchema = new mongoose.Schema({
name: {
type: String,
trim: true,
required: true
},
email: {
type: String,
trim: true,
required: true
},
hashed_password: {
type: String,
required: true
},
salt: String,
...
});
// virtual field
userSchema
.virtual("password")
.set(function(password) {
// create temporary variable called _password
this._password = password;
// generate a timestamp
this.salt = uuidv1();
// encryptPassword()
this.hashed_password = this.encryptPassword(password);
})
.get(function() {
return this._password;
});
// methods
userSchema.methods = {
authenticate: function(plainText) {
return this.encryptPassword(plainText) === this.hashed_password;
},
encryptPassword: function(password) {
if (!password) return "";
try {
return crypto
.createHmac("sha1", this.salt)
.update(password)
.digest("hex");
} catch (err) {
return "";
}
}
};
uuidv1 does generate a unique output everytime which is why you save that as salt in the user model
so uuid creates salt which is like alphabet for crypting strings, uuid has like v1, v2 ... check out their npm doc, i checked it and it was simple, then your userSchema encryptPassword crypts your password using crypto (you imported it in user model) based on that "salt" alphabet and you store the outcome as hashed_password which in future will be used in comparison, based on the saved salt every time
I have an array (bookedby) in a Mongoose model defined like this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BarSchema = new Schema({
date: {
type: Date,
required: true
},
barid: {
type: String,
required: true
},
bookedby: {
type: [String],
required: true
},
});
module.exports = mongoose.model('Bar', BarSchema);
I update it with following function, called by a nodejs express router:
const Bars = require("../../models/bars");
const { getToday } = require('../../utils');
module.exports = function(req, res) {
const { barid } = req.body;
const { username } = req.user;
const date = getToday();
if( !barid ) return res.json({ success: false, error: 'Please specify parameter \'barid\'.'})
Bars.findOne({ barid, date }, function (err, bar) {
if (err) return next(err);
if (!bar || bar.bookedby.indexOf(username) === -1) return res.json({ error: `Bar is not booked yet.` });
// Someone booked the bar
const index = bar.bookedby.indexOf(username);
bar.bookedby.splice(index, 1);
bar.save(err => {
if (err) res.json({ error: `Error saving booking.` });
else res.json({ success: true });
});
});
};
Everything works fine, except when I remove the last item from the bookedby array. Then the save() function doesn't update the database. The last item remains there. I guess it has something to do with mongodb optimizing empty arrays, but how can I solve this?
According to the Mongoose FAQ:
http://mongoosejs.com/docs/faq.html
For version >= 3.2.0 you should use the array.set() syntax:
doc.array.set(3, 'changed');
doc.save();
If you are running a version less than 3.2.0, you must mark the array modified before saving:
doc.array[3] = 'changed';
doc.markModified('array');
doc.save();
I using angluarjs with mongodb.
I have schema is called array based schema.
schema structure :
var Schema = new Schema({
UnitId: String,
UnitName: String ,
Details1:[{
Details1ID:String,
Name:String,
Amount:Number
}],
Details2:[{
Details2ID:String,
Name:String,
Amount:Number
}],
Details3:[{
Details3ID:String,
}],
I want query for inserting the req.body for only Details3.
how to do this?
NOTE:Req.body is Dynamic value
first, you need to add { strict : false } options to your schema
var schema = new mongoose.Schema({
// ..
}, {
strict: false
})
module.exports = mongoose.model('MyModel', schema, 'myModel');
then create model with partial data
// Node.js server side
var model = new MyModel({
// UnitId: "xxx",
Details3: [...whatever]
});
model.save((error, data) => {
console.log("model has been saved", data);
});
I'm building a MEANjs app and I have two schemas: user and a claim. I want to be able to reference user information from a claim.
Right now I can successfully access the display name in my view by using the expression {{vm.claim.user.displayName}}. How do I access the other properties of the embedded user schema?
For example, I'd like to be able to reference a user's firstName and lastName. Something like {{vm.claim.user.firstName}} doesn't yield any result in my view.
user.server.model.js
/**
* User Schema
*/
var UserSchema = new Schema({
firstName: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your first name']
},
lastName: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your last name']
},
displayName: {
type: String,
trim: true
}
});
mongoose.model('User', UserSchema);
claim.server.model.js
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Claim Schema
*/
var ClaimSchema = new Schema({
description: {
type: String,
default: '',
required: 'Please fill Claim description',
trim: true
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.Types.ObjectID,
ref: 'User'
}
});
mongoose.model('Claim', ClaimSchema);
If you want use User schema in Claim schema you can do it like this:
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
User = require('./../models/user'); //proper path here
var UserSchema = require('mongoose').model('User').schema;
/**
* Claim Schema
*/
var ClaimSchema = new Schema({
description: {
type: String,
default: '',
required: 'Please fill Claim description',
trim: true
},
created: {
type: Date,
default: Date.now
},
user: {
type: UserSchema,
ref: 'User'
}
});
mongoose.model('Claim', ClaimSchema);
and User schema needs export statement. Replace mongoose.model('User', UserSchema); with:
exports.UserSchema = UserSchema;
module.exports = mongoose.model('User', UserSchema);
Regarding problems with proper path in dependencies, './../models/user' should work for
├── server
| ├── models
| | └──user.server.model.js
| └── server.js
I would like to ask if there is anyone getting the same response on JSON format:
Objectdata: "User is not authorized"headers: (name) {status: 403statusText: "Forbidden"
Scenario:
User A post a product and add comment on the product.
Result: Successful.
User B comment on the same product:
Result: User is not authorized.
The code I'm using to update the product comment is here:
applicationname/`
// Add comment to Product
$scope.comment = function(){
// console.log("name: ",$scope.user);
// console.log("textarea: ",this.commentarea);
var comment = {
name: $scope.product.user.displayName,
text: this.commentarea
};
$scope.product.comments.push(comment);
$scope.product.$update(function() {
console.log('success update');
}, function(errorResponse) {
console.log('success error', errorResponse);
});
};
This is the server side.
'use strict';
/**
* Module dependencies.
*/
var init = require('./config/init')(),
config = require('./config/config'),
mongoose = require('mongoose'),
chalk = require('chalk');
/**
* Main application entry file.
* Please note that the order of loading is important.
*/
// Bootstrap db connection
var db = mongoose.connect(config.db, function(err) {
if (err) {
console.error(chalk.red('Could not connect to MongoDB!'));
console.log(chalk.red(err));
}
});
// Init the express application
var app = require('./config/express')(db);
// Bootstrap passport config
require('./config/passport')();
// Start the app by listening on <port>
app.listen(config.port);
// Expose app
exports = module.exports = app;
// Logging initialization
console.log('MEAN.JS application started on port ' + config.port);
If your Products schema looks like this:
var ProductSchema = new Schema({
created: {
type: Date,
default: Date.now
},
title: {
type: String,
default: '',
trim: true,
required: 'Title cannot be blank'
},
comments: [{
type: String,
default: '',
trim: true
}]
});
And you have restricted your products route in your app/routes/products.server.routes.js file like so:
app.route('/products/:productId')
.get(products.read)
.put(users.requiresLogin, products.hasAuthorization, products.update)
.delete(users.requiresLogin, products.hasAuthorization, products.delete);
Then a non-authorized user cannot add a comment because they can't update the Product record.
You probably want to create a separate CommentsSchema and use the Mongoose ObjectId type to create a one-to-many relationship with the product:
var CommentSchema = new Schema({
product: ObjectId,
content: {
type: String,
default: '',
trim: true,
required: 'Content cannot be blank'
},
})
That will preserve the security of your product and allow non-authorized users to comment, but would require you to do slightly more complex queries to get your comments in your product view.