使用mongoose 4.9.4,我有两个模型,一个用户模型和一个客户模型。
客户始终附加到用户(用户1-n客户)。
现在要在前面创建一个Customer,我使用表单中的下拉列表从用户中选择一个唯一属性(称为" trigramUser"),使用此属性检索用户objectId并传递它是新人的一个属性。
createCustomer方法:
customerController.js
exports.createCustomer = (req, res) => {
console.log('Creation of the customer '+req.body.siretCustomer+' in progress.');
console.log('Worker attached to the customer '+req.body.userCustomer+' .');
database.getConnection();
user.findOne( { trigramUser: req.body.userCustomer } , '_id', (err, id) => {
var newCustomer = {
sireCustomer : req.body.siretCustomer,
// attributes...
userCustomer : id.str
};
console.log('ID worker : '+id.str+' .');
customer.create(newCustomer, (err) => {
if (err) return res.status(500).json(err.stack);
res.status(200).json(
{ message: 'Customer '+req.body.siretCustomer+'
has been successfully created.' }
);
});
});
};
customer.js
var mongoose = require('mongoose'), Schema = mongoose.Schema;
var customerSchema = new Schema({
siretCustomer:
{ type: String, required: true, minlength: 15, maxlength: 15 },
// attributes ...
userCustomer:
[{ type: Schema.Types.ObjectId, ref: 'User' }],
}, { collection: 'customer' });
module.exports = mongoose.model('Customer', customerSchema, 'customer');
user.js的
var mongoose = require('mongoose'), Schema = mongoose.Schema;
var userSchema = new Schema({
trigramUser:
{ type: String, required: true },
// attributes...
customersUser:
[{ type: String, ref: 'Customer'}]
}, { collection: 'user'});
module.exports = mongoose.model('User', userSchema, 'user');
但是,对于createCustomer方法,控制台会在我提交表单时显示:
Creation of the customer 987987987987987 in progress.
Worker attached to the customer PLD .
ID worker : undefined .
因此req.body.userCustomer到达user.find({}, '_id',
方法。
现在,如果我用Mongo写作:
db.user.findOne({trigramUser:'PDL'})._id.str;
输出为5988897d7b55ba0548d95da6
。
为什么当我在方法user.findOne({trigramUser: req.body.userCustomer}, '_id',
中打印req.body.userCustomer(字符串' PDL')时,字符串为空且查询无效?