Skip to content

Instantly share code, notes, and snippets.

@bajtos
Last active August 29, 2015 14:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bajtos/348e1468d112180d4223 to your computer and use it in GitHub Desktop.
Save bajtos/348e1468d112180d4223 to your computer and use it in GitHub Desktop.
Model.updateAttributes
var loopback = require('loopback');
var app = loopback();
var Car = loopback.createModel('Car');
Car.observe('before save', function(ctx) {
console.log('before save %j', ctx);
return Promise.resolve();
});
//app.dataSource('db', { connector: 'memory' });
app.dataSource('db', { connector: 'mongodb' });
app.model(Car, { dataSource: 'db' });
var id, c1, c2;
Car.create({ color: 'red', age: 1 })
.then(function(car) {
id = car.id;
})
.then(function() {
return Car.findById(id).then(function(car) { c1 = car; });
})
.then(function() {
return Car.findById(id).then(function(car) { c2 = car; });
})
.then(function() {
// Simulate two "PUT /car/:id" requests running in parallel
return Promise.all([
c1.updateAttributes({ color: 'white' }),
c2.updateAttributes({ age: 2 })
]);
})
.then(function() {
return Car.findById(id).then(function(car) {
console.log('RESULT', car);
process.exit();
});
});
before save {"instance":{"color":"red","age":1}}
before save {"where":{"id":1},"data":{"color":"white"}}
before save {"where":{"id":1},"data":{"age":2}}
RESULT { color: 'white', age: 2, id: 1 }
before save {"instance":{"color":"red","age":1}}
before save {"where":{"id":"54f81156ac57108d1ee37985"},"data":{"color":"white"}}
before save {"where":{"id":"54f81156ac57108d1ee37985"},"data":{"age":2}}
RESULT { color: 'white', age: 2, id: 54f81156ac57108d1ee37985 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment