Reputation: 27
So I'm trying to build a shop with Keystone step by step. My problem is that I don't know and can't find how to add a relation between order and user into mongodb.
This is the checkout.js
var keystone = require('keystone');
var Order = keystone.list('Order');
exports = module.exports = function (req, res) {
var view = new keystone.View(req, res);
var locals = res.locals;
locals.section = 'checkout';
locals.formData = req.body || {};
locals.validationErrors = {};
locals.orderSubmitted = false;
locals.orderer = req.user; // <-
// On POST requests, add the Order item to the database
view.on('post', { action: 'checkout' }, function (next) {
var newOrder = new Order.model();
var updater = newOrder.getUpdateHandler(req);
updater.process(req.body, {
flashErrors: true,
fields: 'sum',
errorMessage: 'There was a problem submitting your order:',
}, function (err) {
if (err) {
locals.validationErrors = err.errors;
} else {
locals.orderSubmitted = true;
}
next();
});
});
view.render('checkout');
};
This is the Order.js model
var Order = new keystone.List('Order');
Order.add({
orderer: { type: Types.Relationship, ref:'User' },
sum: { type: Types.Money, format: '0.0,00' },
createdAt: { type: Types.Datetime, default: Date.now },
});
This is the User.js model
var User = new keystone.List('User');
User.add({
name: { type: Types.Name, required: true, index: true },
email: { type: Types.Email, initial: true, required: true, unique: true, index: true },
password: { type: Types.Password, initial: true, required: true },
});
User.relationship({ ref: 'Order', path: 'orders', refPath: 'orderer' });
Upvotes: 1
Views: 189
Reputation: 1493
You need to push a User ObjectId in your Order object to be able to use the populate function in order to read your results. For this you can push directly the id as a string and it with auto cast it :
var newOrder = new Order.model({
orderer: '560e19e0228dd7ff3a034f19',
sum: '1.23',
});
Note, if you need/want to specify that it is an object, you can use mongodb objectId :
var ObjectId = require('mongodb').ObjectID;
var newOrder = new Order.model({
orderer: ObjectId('560e19e0228dd7ff3a034f19'),
sum: '1.23',
});
And in your updater, add your fields for format validation :
updater.process(req.body, {
flashErrors: true,
fields: 'orderer, sum',
errorMessage: 'There was a problem submitting your order:',
},
Upvotes: 2