node.js - Mongoose无法保存嵌入文档

标签 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 中?

谢谢。

最佳答案

您不要将嵌入文档作为整个文档保存在另一个文档中。您必须保存文档的“_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
});  

现在,在“架子”处保存您想要填充的相应文档。当您要获取文档时,请像 -

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

关于node.js - Mongoose无法保存嵌入文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43228482/

相关文章:

javascript - Node.js+Express 和 CoffeeScript 的 IDE 或编辑器

node.js - 使用 sequelize 迁移将关联添加到非默认模式

node.js - NodeJS 文件系统同步和性能

ruby-on-rails - 关于从 MongoMapper 迁移到 Mongoid 的建议?

mysql - 我应该在 node.js 中使用哪个数据库?

node.js - 如何在 mocha 和 mongoDB 中使用 chai 向 Node 发出发布请求

javascript - 无法在 localhost 上启动 Node.js 的 MongoDB

node.js - 用于多项选择题和答案的 MongoDB 模式设计

node.js - 在 Jade 中使用 HTML 是否被认为是不好的做法?

node.js - 如何在expressjs中调用静态html页面