1

私は2つの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オブジェクトを保存すると、保存された _id に割り当てられませんContact

しかし、このスキーマを使用すると:

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' 
    }] 
}

私は何が欠けていますか?

4

1 に答える 1

0

だから、私はここで完全にオフでした。私の問題は、スキーマを要求する方法でした。私が使用していた:

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

module.exports = ContactSchema;スキーマを取得しますが、contact.js ファイルの末尾には追加しませんでした。

この質問のおかげで: MongoDB: How to use one schema as sub-document for different collection defined in different files 解決できました (ただし、他のすべてが機能していたため、世界で最も奇妙な動作です)。

于 2016-02-02T17:47:05.437 に答える