KeystoneJS 获取用户数据 mongodb

KeystoneJS getting data of user into mongodb

所以我正在尝试逐步使用 Keystone 建立一家商店。我的问题是我不知道也找不到如何将订单和用户之间的关系添加到 mongodb 中。

这是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');
};

这是Order.js模型

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 },
 });

这是User.js模型

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' });

您需要在 Order 对象中推送一个 User ObjectId 才能使用填充函数来读取结果。为此,您可以直接将 id 作为字符串推送并自动转换它:

var newOrder = new Order.model({ orderer: '560e19e0228dd7ff3a034f19', sum: '1.23', });

注意,如果你need/want指定它是一个对象,你可以使用mongodb objectId :

var ObjectId = require('mongodb').ObjectID;

var newOrder = new Order.model({ orderer: ObjectId('560e19e0228dd7ff3a034f19'), sum: '1.23', });

然后在您的更新程序中,添加用于格式验证的字段:

updater.process(req.body, { flashErrors: true, fields: 'orderer, sum', errorMessage: 'There was a problem submitting your order:', },