I have two models which user and merchant. I will send JSON data from UI.
In Sequelize, I have used "include" option to insert the data like below.
models.user.create(req.body, { include: [models.merchant] });
It is working well as expected. So I have tried to update the data like below.
var filter = {
where: { id: id },
include: [
models.merchant
]
};
models.user.update(req.body, filter);
The above code is updating user data only. Association is not working in the update. I don't know what is wrong with this.
Please anyone help to resolve this issue.
Thanks in advance.
The behaviour your asking for simply can't be done with a single update call. If you check the docs for the update function, there isn't an include option, i.e. sequelize can only build an update query for the table of the model who's update function is called.
You will have to update the associations separately. I advise that you put those updates inside a transaction to avoid any issues with multiple updates to the same object happening at the same time.
Related
Is it possible to use set (within the context of a transaction) to create a document with some object, but only update it with a subset of properties?
For example, I have a use case where I'd like to create or update a document, but in the update case only certain fields should be merged. In the code below, created should only be written on document creation (and not on update).
I've tried mergeFields in SetOptions which I thought would only apply to the update case, but seems to apply to the write case as well and causes created to be omitted when creating the document.
If that's the intended behaviour of SetOption is there another way to achieve this?
t.set(docRef,
{
name: 'Alice',
updated: admin.firestore.FieldValue.serverTimestamp(),
created: admin.firestore.FieldValue.serverTimestamp(),
},
{ mergeFields: ['name', 'updated'] });
Node.js Admin SDK 9.2.0
Seems like your transaction will first have to read the document with get() to create or update, then make a decision about what to pass to set() in order to make sure the document contains the correct fields. A single set() cannot make this decision for you. So, something like:
const snap = await t.get(docRef)
if (snap.exists) {
t.update(docRef, ...)
}
else {
t.create(docRef, ...)
}
Im using Objection.js as my ORM for a simple rainfall application. I need to be able to dynamically update and entry of one table when a lower level tables entires has been updated. To do this I need the whole entry I am updating so I can use that data to correctly update the dynamically updated entry.
Im using the $afterUpdate hook for the lower level table entry which. The issue I am having is that when I log this within the $afterUpdate hook function it only contains the properties for the parts of the entry I want to update. How can I get the entire entry? Im sure I could get the record by running an additional query to the DB but I was hoping there would be away to avoid this. Any help would be appreciated
I think, as of right now, you can only get the whole model with an extra query.
If you are doing the update with an instance query ($query) you can get the other properties from options.old.
Query:
const user = await User.query().findById(userId);
await user.$query()
.patch({ name: 'Tom Jane' })
Hook:
$afterUpdate(opt, queryContext) {
console.log(opt.old)
}
Patch
If you don't need to do this in the hook, you might want to use patch function chained with first().returning('*') to get the whole model in a single query, it's more efficient than patchAndFetchById in postgreSQL. Like stated in the documentation.
Because PostgreSQL (and some others) support returning('*') chaining, you can actually insert a row, or update / patch / delete (an) existing row(s), and receive the affected row(s) as Model instances in a single query, thus improving efficiency. See the examples for more clarity.
const jennifer = await Person
.query()
.patch({firstName: 'Jenn', lastName: 'Lawrence'})
.where('id', 1234)
.returning('*')
.first();
References:
http://vincit.github.io/objection.js/#postgresql-quot-returning-quot-tricks
https://github.com/Vincit/objection.js/issues/185
https://github.com/Vincit/objection.js/issues/695
I'm using Sequelize.js for ORM and have a few associations (which actually doesn't matter now). My models get get and set methods from those associations. Like this (from docs):
var User = sequelize.define('User', {/* ... */})
var Project = sequelize.define('Project', {/* ... */})
// One-way associations
Project.hasOne(User)
/*
...
Furthermore, Project.prototype will gain the methods getUser and setUser
according to the first parameter passed to define.
*/
So now, I have Project.getUser(), which returns a Promise. But if I call this twice on the very same object, I get SQL query executed twice.
My question is - am I missing something out, or this is an expected behavior? I actually don't want to make additional queries each time I call the same method on this object.
If this is expected - should I use custom getters with member variables which I manually populate and return if present? Or there is something more clever? :)
Update
As from DeBuGGeR's answer - I understand I can use includes when making a query in order to eager load everything, but I simply don't need it, and I can't do it all the time. It's waste of resources and a big overhead if I load my entire DB at the beginning, just to understand (by some criteria) that I won't need it. I want to make additional queries depending on situation. But I also can't afford to destroy all models (DAO objects) that I have and create new ones, with all the info inside them. I should be able to update parts of them, which are missing (from relations).
If you use getUser() it will make the query call, it dosent give you access to the user. You can manually save it to project.user or project.users depending on the association.
But you can try Eager Loading
Project.find({
include: [
{ model: User, as: 'user' } // here you HAVE to specify the same alias as you did in your association
]
}).success(function(project){
project.user // contains the user
});
Also e.g of getUser(). Dont expect it to automatically cache user and dont override this cleverly as it will create side effects. getUser is expected to get from database and it should!
Project.getUser().then(function(user){
// user is available and is a sequelize object
project.user = user; // save project.user and use it till u want to
})
The first part of things is clear - every call to get[Association] (for example Project.getUser()) WILL result in database query.
Sequelize does not maintain any kind of state nor cache for the results. You can get user in the Promisified result of the call, but if you want it again - you will have to make another query.
What #DeBuGGeR said - about using accessors is also not true - accessors are present only immediately after a query, and are not preserved.
As sometimes this is not ok, you have to implement some kind of caching system by yourself. Here comes the tricky part:
IF you want to use the same get method Project.getUser(), you won't be able to do it, as Sequelize overrides your instanceMethods. For example, if you have the association mentioned above, this won't work:
instanceMethods: {
getUser: function() {
// check if you have it, otherwise make a query
}
}
There are few possible ways to fix it - either change Sequelize core a little (to first check if the method exists), or use some kind of wrapper to those functions.
More details about this can be found here: https://github.com/sequelize/sequelize/issues/3707
Thanks to mickhansen for the cooperation on how to understand what to do :)
I've got a big problem, i'm trying to use model associations in Mongoose because it would be really useful but there's something i don't get ...
Let's say there's a User model with a schema like ... (among others)
user_geos : [{
type: Mongo.Schema.ObjectId,
ref: 'UserGeo',
}]
And there's a UserGeo model with this schema ... (among others)
_user: {
type: Mongo.Schema.ObjectId,
ref: 'User'
}
Very simple, when I'm creating a new UserGeo, it should automatically add it to the user_geos array within User, right ?
user_geo_infos._user = user.id;
db.UserGeo.create(user_geo_infos, function(error, user_geo) {
catches.error(error);
console.log(user_geo);
});
The big problem I got is when i'm creating it, it fills correctly the "_user" field in UserGeo in the database but the User model doesn't fill itself. The array stay empty ("[]"). A detail but you really understood is UserGeo got one User and User got many UserGeo.
I'm really stuck, did i do something wrong ? I checked everywhere and read the Mongoose documentation like 10 times now ...
Any idea ? Thanks people ;)
Very simple, when I'm creating a new UserGeo, it should automatically add it to the user_geos array within User, right ?
Nope. There is a lot less magic/automatic stuff here than you are hoping for. Mongodb, as well as mongoose, will only ever act upon a single collection at a time. This will do the querying automatically when you load records and use the mongoose .populate helper, but it doesn't help you writing across collections.
Ok I tried to make it manually and it works but i'm quite disappointed ... Looks like this ...
db.UserGeo.create(user_geo_infos, function(error, user_geo) {
db.User.findOne(user.id, function(error, user) {
catches.error(error);
user.user_geos.push(user_geo.id);
user.save();
});
catches.error(error);
console.log(user_geo);
});
After I create a UserGeo I get the User and then push the new data to the User field ...
This is solution is heavy, maybe make some helpers would make it lighter .. Thanks anyway :)
I'm working on a custom adapter in sails#0.10.0-rc4 which will support associations but I am having trouble getting them working in conjunction with my adapter. My configuration is a one-to-many association between article and stats. My models and adapter are setup like this:
// api/models/article.js
module.exports = {
connection: ['myadapter'],
tableName: 'Knowledge_Base__kav',
attributes: {
KnowledgeArticleId: { type: 'string', primaryKey: true }
stats: {
collection: 'stats',
via: 'parentId'
}
}
// api/models/stats.js
module.exports = {
connection: ['myadapter'],
tableName: 'KnowledgeArticleViewStat',
attributes: {
count: 'integer',
ParentId: {
model: 'article'
}
}
}
// adapter.js
find: function(connectionName, collectionName, options, cb) {
console.dir(options)
// output
// {where: null}
db.query(options, function(err, res)) {
cb(err, res)
}
}
However, when I try to populate using Article.find().populate('stats').exec(console.log()), my adapter gets {where: null} as options when I would expect it to receive {where: {parentId: [<some-article-id>]}}. It will return a list of articles to me but the field which is supposed to be populated from another model (stats) is just an empty list.
I feel like this is related to the fact that my adapter is not getting the proper where param to search for the related model on the primary key. To test this further, I setup a test one-to-many relationship using the the sails-mongo adapter. In this case the adapter did receive params I expected and the association worked fine.
Does anyone have any idea on why .populate('stats') wouldn't be sending the proper "where" params to my adapter?
Update 3/7
So it seems like what happens in associations is that SomeModel.find() will hit the adapter once and then .populate('othermodel') hits the adapter again using the primary key of the first request. Then the results of both are joined together. In my case, the second hit against the adapter isn't happening for some unknown reason.
Update
The original issue was related to an attribute naming error that's mentioned in the comments below. However, there still appears to be some issue with the final population step mentioned by particlebanana:
Final step will: Take all of the query results from all the returned query operations
and combine them in-memory to build up a result set you can return in
the exec callback.
I'm seeing that all required queries are now firing but they are failing to actually populate the alias. Here's the call with some added debugging output in the form of a gist for easier consumption: https://gist.github.com/jasonsims/9423170
It looks like you are on the right track! The way the operation sets get built up, the .find() on the Article should run with the first log (empty where) and the second query should get run with the parentId criteria in the log. The second query isn't running because it can't build up that parentId array of primary keys when you don't return anything from the first query.
Short answer: you need to return something in the find callback to see the second log, which should match your expected criteria.
The query lifecycle looks something like this:
Check if all query pieces are on the same connection, if not break out which queries will run on which connections
For all queries on a single connection, check if the adapter supports native joins (has a .join() method, if so you can pass the criteria down and let the adapter handle the joins.
If no native join method is defined run the "parent" operation (in this case the Article.find())
Use the results of the parent operation to build up criteria for any populations that need to run. (The parentId array in your criteria) and run the child results.
Take all of the query results from all the returned query operations and combine them in-memory to build up a result set you can return in the exec callback.
I hope that helps some. Shoot me the url of your repo and I will look through it, if it's able to be open sourced, and can help some more if you come across any issues.
Just to summarize, there were multiple issues going on here which were causing associations not to populate:
Custom primary keys
There was a problem with waterline when joining data from models using custom primary keys. #particlebanana fixed this in 8eff54b and it should be included in the next rc of waterline (waterline#0.10.0-rc5).
Malformed SOQL query
When waterline queries the adapter for a second time in order to acquire the child rows, it does so using { foreignKey: [ value ] }. Since the value was a list, jsforce was incorrectly generating the SOQL query since it expected all list values to be accompanied by either $in or $nin operators. I addressed this issue in github/jsforce#9 and it's now included in jsforce#1.1.2.
Model attributes are case sensitive
The models in my project were defined in snakeCase but the json response from Salesforce was using EveryWordCapitalized. This causes 1-to-many joins in waterline to reduce the many child records to one when it runs _.uniq(childRows, pk). Since the model has defined pk == id but the actual value returned from Salesforce is pk == Id, this call to uniq blows away all child records but one. I'm not entirely sure if this should be a waterline bug or not but fixing the capitalization in the model attribute definitions resolved this.