I want to map json data from request.params to model in my controller class.
It have some action in controller before save model to database.
Does it has the solution to auto map json data to model object without manually do this?
var email = req.body.email;
var phone = req.body.phone;
If I understand your question correctly, then yes.
I'll often build forms like this:
<input type="text" name="data[email]" value="ex#example.com">
<input type="text" name="data[phone]" value="1234567890">
In your controller:
var data = req.param('data')
// data is now = {email : 'ex#example.com', phone : '1234567890'}
And when updating database:
User.create(data).exec(funtion(e,r){
console.log(e||r)
// if there is no error, object r should contain:
// {
id : <id>,
email : 'ex#example.com',
phone : '1234567890',
createdAt : <date>,
updatedAt : <date>
}
})
Related
I have a problem in input data-binding for one of our ionic 3 application. Whenever input changes which is changing the array values of different arrays of same type.
Here is my HTML
<ion-list>
<ion-item-sliding *ngFor="let item of storageItem ; index as i">
<div class ="itemList">
<input type="number" [value] ="item.storageOrderQuantity" (blur)="updateInputItemValue(item)"
[(ngModel)]="item.storageOrderQuantity" />
</div>
</ion-item-sliding>
</ion-list>
When ever input value changes, it is updating 'storageItem' array along with other arrays which has the same object(there are some other arrays 'item').
Here is my arrays declaration. Item is a model class.
item: Item[];
storageItem: Item[] = [];
storageItem' is a subset of 'item
Can anybody tell what would be the mistake in data-biding?
You have mentioned that storageItem is a subset of item
You probably already know this, Arrays and Object use concept of assign-by-reference. If you don't know this then read below article on Medium.
https://medium.com/#naveenkarippai/learning-how-references-work-in-javascript-a066a4e15600
So if you have the same object in both the arrays then updating one array will update the another,
const obj = { name : 'value' };
const arr1 = [1,2,3,obj];
const arr2 = [4,5,6,obj];
obj.name = 'yash'; // both arrays will have updated object
Now if you want to avoid this, then you can create a copy of the object before using it in another array.
Take reference from https://flaviocopes.com/how-to-clone-javascript-object/
item: Item[] = [
{ id : 'item1', list : [] },
{ id : 'item2', list : [] },
{ id : 'storageItem', list : [...storageItem] }
];
storageItem: Item[] = [list of storage items];
Now storageItem and item > id='storageItem' point to different arrays.
So your template will only update the storageItem now.
Hi I have the next model in backboneJS:
var Type = Backbone.Model.extend({
url : "/api/SomeRoute"
});
var model = new Type({id:"MyAlias"});
model.fetch();
On the rest part In SomeRoute I have 2 actions which returns my Model. First which recieves the Id and returns the Model by Id and second without parameters which return the collection. But when I call fetch() in JS, it doesn't send the Id in the request. What I'm doing wrong?
If there is an id attribute specified in a model. Then the fetch request will be like /api/SomeROute/id
Instead of url give urlRoot. If urlRoot is specified then the models id will be appended.
var Type = Backbone.Model.extend({
urlRoot : "/api/SomeRoute"
});
Rewrite your url to next:
var type = Backbone.Model.extend({
url: function(){
return "/api/SomeRoute/" + this.get("id");
}
});
var model = new Type({id: "SomeId"});
model.fetch();
I have users model that can hold multiple notifications. In the NotificationSchema the notifier holds users ID and it references the users model. When I execute the following query :
User.find().populate('notifications.notifier').exec(function(err,users){
//users[0].notifications[0].notifier
//I am getting all fields from the referenced user
//I don't want the whole document but some fields only
});
How can someone Limit / Restrict the fields that should be available while referencing to some model.
Here is the users model
var NotificationSchema =new Schema({
notifier : {type:Schema.Types.ObjectId, ref:'users'},
//How could I say :
//notifier : {type:Schema.Types.ObjectId, ref:'users', fields:['_id', 'name']}
//because I know what fields do I need from referenced model for this Schema.
__SOME__
__OTHER__
__FIELDS__
});
var UsersSchema = new Schema({
name : {given:String, middle:String, family:String}
email:String,
password:String,
notifications : [NotificationSchema]
});
var Users = mongoose.model('users', UsersSchema);
BTW, I do not have separate model for NotificationSchema.
If this feature is not available out of the box how could I implement it manually. Am I missing some docs? Please let me know the robust way of doing it.
I found it in mongoose docs
I found the answer in Field Selection Section of the documentation
User.find().populate('notifications.notifier', '_id name').exec(function(err, users) {
//users[0].notifications[0].notifier ^^^^^^^^^ HOW FUNNY
//Yes I am getting '_id' and 'name' fileds only
});
js and mongodb.I have created a model file named models like the one given below
User = new Schema({
username : String
, password : String
, created_at : Date
});
mongoose.model('User', User);
exports.defineModels = defineModels;
In app.js i have called the defineModels like this:
var models = require('./models'),
models.defineModels(mongoose, function() {
app.User = User = mongoose.model('User');
db = mongoose.connect(app.set('db-uri'));
})
I can't call save method directly on User or can I?
i want to save data in User what could be the function for the same.any answer will be appriciated
To do what you want, you should have something like this:
var user = new User({username: 'Name', password: 'unsecure'});
user.save();
There are a few things odd with your code, so I highly suggest going over a tutorial that uses express and mongoose to create a sample site (most likely you can find a blog).
Here is one I made: https://github.com/mathrawka/node-express-starter
Good luck!
I'm working on a strongly-typed edit form for a MVC model that contains a collection of child models (Document contains many LocalizedDocuments). Each document can contain 0, 1, or many localized documents, and every localized document has an input type="file" to allow the user to upload a new version of the file.
To render the edit fields for each LocalizedDocument I have a strongly-typed partial view that contains the fields for the LocalizedDocument, and then in my edit view use Html.EditorFor(model => model.Document.LocalizedDocuments).
When the form is posted, each of my LocalizedDocument fields are prefixed with LocalizedDocument[i], as expected. However, how can I get it so the file input is also prefixed with LocalizedDocument[i], so I can relate the file upload to the appropriate LocalizedDocument?
Tell me if I'm interpreting this question wrong. You have documents that you need to upload that belongs to a parent table or you need to assign these documents a specific id after uploading multiple of them?
I'll be using Uploadify.
You will have to know the Id of the LocalizedDocument. You will also only be able to upload 1 at a time. (each file is a separate server call)
First you have to assign the Id of the LocalizedDocument to the data that will be sent to the server.
<script type="text/javascript">
var auth = "<%: Request.Cookies[FormsAuthentication.FormsCookieName]==null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value %>";
var ASPSESSID = "<%: Session.SessionID %>";
$(document).ready(function () {
$('#file_upload').uploadify({
'uploader': '/Content/uploadify.swf',
'script': '<%: Url.Action("Upload", "Documents") %>',
'cancelImg': '/Content/Images/cancel.png',
'folder': '/uploads',
'scriptData': { ASPSESSID: ASPSESSID, AUTHID: auth, DocumentId: <%: Model.LocalizedDocumentId %>},
'auto':true,
'multi': true
});
});
</script>
Controller:
public ActionResult InsertImages(HttpPostedFileBase FileData, int DocId){ }