猫鼬子模式不生成_id

Mongoose sub-schema not generating _id

我有两个 Schema 对象:

contact.js:

/**
 * Contact Schema
 */
var ContactSchema = new Schema({
    name: String,
    role: String,
    phone: String,
    email: String,
    primary: Boolean
}, {timestamps: {createdAt: 'created', updatedAt: 'updated'}, _id: true, id: true});

client.js:

/**
 * Client Schema
 */
var ClientSchema = new Schema({
    name: {
        type: String,
        required: true,
        trim: true
    },
    comments: {
        type: String,
        trim: true
    },
    creator: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    contacts: [ContactSchema],
    address: String,
}, {timestamps: {createdAt: 'created', updatedAt: 'updated'}});

唉,当我保存Client对象时,保存的Contact没有分配_id。

但是当我使用这个模式时:

client.js:

/**
 * Client Schema
 */
var ClientSchema = new Schema({
    name: {
        type: String,
        required: true,
        trim: true
    },
    comments: {
        type: String,
        trim: true
    },
    creator: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    contacts: [{
        name: String,
        role: String,
        phone: String,
        email: String,
        primary: Boolean
    }],
    address: String,
}, {timestamps: {createdAt: 'created', updatedAt: 'updated'}});

联系人使用自动生成的 _id 保存。

我拯救客户的方式非常直接:

var client = new Client(req.body);
client.creator = req.user;
client.save(function (err) {
    if (err) {
        console.log(err);
        return res.status(500).json({
            error: 'Cannot save the client'
        });
    }

    res.json(client);
});

而req.body的内容是:

{ 
    name: 'A name for the client',
    contacts: [ { 
        name: 'A name for the contact',
        email: 'noy@test.com',
        role: 'UFO' 
    }] 
}

我错过了什么?

所以,我完全离开了这里。我的问题是我需要模式的方式。 我正在使用:

var ContactSchema = require('./contact');

获取架构,但我没有在 contact.js 文件末尾添加 module.exports = ContactSchema;

感谢这个问题:MongoDB: How to use one schema as sub-document for different collections defined in different files 我能够解决我的问题(虽然这是世界上最奇怪的行为,因为其他一切都正常)。