I understand that Sequelize has a Model function for setting multiple assocations in a hasMany relationship, like user1.setFollowing(), as well as a function to add a single assocation, like user1.addFollowing(). But the latter does not let you pass an array (I receive an error) - is there any function to let you add multiple associations, like user1.addFollowings?
You should use add{ModelName} for add one instance and set{ModelName} for array of instances
Project.hasMany(Task)
Task.hasMany(Project)
project.addTask(task1).success(function() {})
but
project.setTasks([task1, task2]).success(function() {})
example
Related
I want to use two dto's for one query param.
#Query() query: CurrencyTypeDto|PaginationLimitDto
I know I can use inheritance. Maybe there is another way?
NestJs offers something called IntersectionType() to combine two types into one new type (dto), to Implement that you need to:
export class queryDto extends IntersectionType(
CurrencyTypeDto,
PaginationLimitDto,
) {}
then you can use it: #Query() query: queryDto
Ref : intersection
I am not sure if this type of question has been asked before, but I was not able to find anything related to this. In my current project we use Joi schemas to perform the validations. I like the ability to define custom schemas and run validations on the incoming objects using that schema. I have a task where I need to filter out object properties. Something similar to _.pick but the properties are complex and deal with nested objets and arrays. We already have a joi schemas that we have designed to perform validations but I am thinking of using the same to get the specific properties of the object, like filtering object data using that schema. Something like this:
const Joi = require('joi');
const val = {
a: 'test-val1',
b: 'test-val2'
}
const schema = Joi.object({
a: Joi.string()
});
// now the below result have the object with both `a` and `b`
// properties but I want joi to strip the `b` property from the object
const result = schema.validate(value, { allowUnknown: true });
Joi's documentation doesn't mention anything like this. I have come across this(ajv) library which does do what I want but I wanted to know for sure if this can not be achieved using Joi. Thanks in advance.
Joi offers stripUnkown property that can be used to get only the fields defined in the schema.
Does Bookshelf.js provide a method to find a model by it's related model?
I have create the two models Order and OrderStatus. Now, I want to fetch an Order model by it's status. Unfortunately, this approach isn't working anymore, as the load method expects a string or string array now.
const order = await new Order().load({"orderStatus": q => q.where({"userId": userId, "status": 10})});
I've found a library called "bookshelf-eloquent" that adds this functionality. However, I'm using Typescript and this library doesn't provide any type declaration.
This code works, but TypeScript indicates that the property whereHas doesn't exist.
const order = await new Order()
.whereHas("orderStatus", q => q.where({"userId": userId, "status": 10}))
.get()
Either the Bookshelf.js developers have added a new method I haven't seen yet, or I need to have a type declaration file for the bookshelf-eloquent library. Otherwise, I can't use it.
I want to remove all members that a collection has , but I do not want to pass every member ID to .member() method .
waterline documentation explain a way to delete specific members like :
await User.removeFromCollection(3, 'pets')
.members([99,98]);
I want to have sth like :
await User.removeFromCollection(3, 'pets')
.members(['*']);
As far as I can tell, this should be done using .destroy() without a criteria.
Edit (2019-07-10): Added the empty curlies as per the comment from noobular
await User.destroy({}); // Removes all records from your User collection
await User.destroy({name:'Bill'}; // Removes all records from your User collection
where the 'name' is 'Bill'
Docs: .destroy()
Update
After you pointed out I misread your question, I came up with this solution. The docs for .removeFromCollection() states that passing in an array of parent ID's will remove all children in the specified collection, but this does not seem to function as written.
I did however find a working solution for you using .replaceCollection().
await User.replaceCollection(3, 'pets', []);
OR
await User.replaceCollection(3, 'pets').members([]);
Passing in an empty array will replace the current array of associations with the empty array, clearing out the current associations.
Docs: .replaceCollection()
I have Students and Classes with a hasMany association between them.
I do this:
myStudent.setClasses(ids). then(function(result) {
console.log(myStudent.Classes);
});
Questions:
What does result parameter mean inside the then-handler?
Why isn't myStudent.Classes up-to-date with the setClasses() change I made?
How can I have Sequelize update the simple Classes member? I need to return a simple JSON response to the caller.
According to docs, result would be the associated Classes (in you case) when sending them to the .setClasses method.
Therefore, your ids param should be in fact the Classes, perhaps you should require them before
Class.findAll({where: {id: ids}})
.on('success', function (classes) {
myStudent.setClasses(classes)
.on('success', function (newAssociations) {
// here now you will have the new classes you introduced into myStudent
// you say you need to return a JSON response, maybe you could send this new associations
})
})
It's not updating because the queries regarding the associations of objects doesn't rely on you original object (myStudent). You should add the new associations (result var, in your example, newAssociations, in mine) in your existing myStudent.Classes array. Maybe reloading your instance should work as well.
Class.findAll({where: {id: ids}})
.on('success', function (classes) {
myStudent.setClasses(classes)
.on('success', function (newAssociations) {
myStudent.Classes = myStudent.Classes || [];
myStudent.Classes.push(newAssociations);
// guessing you're not using that myStudent obj anymore
res.send(myStudent);
})
})
I hope I answered this one with the previous two answers, if not, could you explain what you mean by updating the Classes member?