【问题标题】:Mongoose sub-schema not generating _idMongoose 子模式不生成 _id
【发布时间】:2016-02-03 01:47:05
【问题描述】:

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

我错过了什么?

【问题讨论】:

  • 您能否请添加您如何生成和保存我认为错误存在的对象。
  • @Sprotte 当然,我已经编辑了这个问题。谢谢!
  • 如何创建Client 模型?
  • @kba 没什么特别的:mongoose.model('Client', ClientSchema);

标签: javascript node.js mongoose mongoose-schema


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2020-10-27
    • 2018-06-25
    • 2017-02-07
    • 2018-05-13
    • 2012-12-07
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多