Mongoose子模式不生成_id

时间:2016-02-02 15:15:44

标签: javascript node.js mongoose mongoose-schema

我有两个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' 
    }] 
}

我错过了什么?

1 个答案:

答案 0 :(得分:0)

所以,我完全不在这里。我的问题是我需要架构的方式。 我正在使用:

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 我能够解决我的问题(世界上最奇怪的行为,因为其他一切都在运作)。