我正在创建一个对象注册(一个Mongoose Schema),我需要在Id
中使用以下行设置User
:registrationId: registration._id});
但是,Id
仍为null
,即使它是回调函数?当我检查数据库时注册有ID和Id当然,但不在回调中。如何在Id
中设置Registration
的{{1}}?
Edit2:改为最小的例子。这打印出两次User
。
null
编辑:这是架构(我遗漏了一些不需要的字段):
exports.create = function(req, res) {
Registration.create(req.body, function(err, registration) {
if(err) { return handleError(res, err); }
console.log(registration._id);
console.log(registration.id);
return res.json(201, registration);
});
};
问题和解决方案:问题是客户端发送属性_id = null,这就是为什么MongoDB / Mongoose没有更新ID。
答案 0 :(得分:2)
您的代码中必定还有其他内容正在影响这一点。这个例子对我有用:
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/createid');
var RegistrationSchema = new Schema({
isReservation: Boolean,
//Id of the trip
tripId: String,
//socialMutuality
codeGerechtige: String,
socialMutualityNumberParent1: String,
socialMutualityNumberParent2: String,
//contact
userId: String,
firstnameContact: String,
lastnameContact: String,
emailContact: String,
streetContact: String,
streetNumberContact: String,
zipcodeContact: String,
busContact: String,
cityContact: String,
phoneContact: String,
gsmContact: String,
socialSecurityNumberContact: String,
//coordinats of person that pays
//child information
//emergency contacts
emergencyContacts: [{
firstName: String,
lastName: String,
phone: String
}],
extraInfo: String
});
var Registration = mongoose.model('Registration', RegistrationSchema);
var reg = {
userId: '1234',
tripId: '2345',
firstnameContact: 'Timothy',
lastnameContact: 'Strimple',
emailContact: 'tim@tstrimple.com'
};
Registration.create(reg, function(err, registration) {
if(err) { throw err; }
console.log(registration._id);
});
我将一个有效的ID写入控制台。
答案 1 :(得分:0)
从req.body中删除_id修复了我的问题。
if(req.body._id === null) {
delete req.body._id;
}