Mongoose无法保存嵌入的文档

时间:2017-04-05 10:26:17

标签: node.js mongodb express mongoose mean-stack

我正在尝试在Mongo DB中创建一个文档,其中包含一个嵌入式文档。该文档的模型/架构如下:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// Cupboard Collection Schema
 var ShelfSchema = new Schema({
 shelf_name: {
    type: String
 },
 shelf_desc: {
    type: String
 }
});

var CupboardSchema = new Schema({
 cupboard_name: {
  type: String,
  required: true,
  unique: true
 },
cupboard_desc: {
 type: String,
 required: true
},
shelf: [ShelfSchema]
},
{
  timestamps: true
});

module.exports = mongoose.model('Cupboard', CupboardSchema);

图像显示了保存文档的代码。 Code for saving document

当我打印" newCupboard"在控制台中,我按照以下格式获取文档:

{
_id: 58e4b972931dc809f4127b0b
cupboard_name: Cupboard A,
cupboard_desc: Cupboard A Details,
shelf: [ {
 shelf_name: Cupboard A,
 shelf_desc: Cupboard A Details,
 _id: 58e4c2742bfc0111dc47f149
 }]
}

但执行后,嵌入式文档没有被保存。没有显示错误。最终结果如下所示:

{
 _id: 58e4b972931dc809f4127b0b
 cupboard_name: Cupboard A,
 cupboard_desc: Cupboard A Details
}

任何人都可以帮我解决这个问题,为什么嵌入式文档没有保存在mongo db中?

感谢。

1 个答案:

答案 0 :(得分:1)

您不将嵌入文档作为整个文档保存在另一个文档中。您必须保存文档的“_id”,并且在获取记录时,您将在查询中调用populate()
所以,让我们假设您必须在Cupboard架构中保存文档,架构将如下所示 -

var CupboardSchema = new Schema({
 cupboard_name: {
  type: String,
  required: true,
  unique: true
 },
cupboard_desc: {
 type: String,
 required: true
},
shelf: {
type: Schema.Types.ObjectId,
ref: 'ShelfSchema'}
},
{
  timestamps: true
});  

现在,在'shelf'保存您要填充的相应文档。当您要获取文档时,请致电populate(),如 -

CupboardSchemaModel.find({_id: <some-id-you-want-to-fetch>}).populate('shelf');