Mongoose对象ID为null

我正在创build一个对象注册(一个Mongoose模式),我需要设置它在User Id与这一行: registrationId: registration._id});

但是,即使它是callback函数, Id仍然是null的? 当我检查数据库的注册有,当然,但不是在callback。 如何设置User RegistrationId

编辑2:改为最小的例子。 这打印出两次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); }); }; 

编辑:这是架构(我遗漏了一些不需要的字段):

 'use strict'; var mongoose = require('mongoose'), Schema = mongoose.Schema; 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 }); module.exports = mongoose.model('Registration', RegistrationSchema); 

问题和解决scheme:问题是客户端发送属性_id = null,这就是为什么MongoDB / Mongoose没有更新ID。

在你的代码中必须有其他的事情正在影响着这个。 这个例子符合我的预期:

 '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。