node.js – Mongoose对象id为null

我正在创建一个对象注册(一个Mongoose Schema),我需要用这一行在User中设置它的Id:registrationId:registration._id});

但是,Id仍然为null,即使它是回调函数?当我检查数据库时注册有ID和Id当然,但不在回调中.如何设置用户注册的ID?

Edit2:改为最小的例子.这打印出两次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);

问题和解决方案:问题是客户端发送属性_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.

点赞