簡體   English   中英

無法將子文檔字段添加到Mongodb架構

[英]Can't Add Subdocument Field to Mongodb Schema

我正在使用mongodb在express中創建一個nodejs應用程序。 我在嵌套模式上遇到了麻煩。 由於某些原因,當我使用db.play.find()。pretty()通過終端在集合中查找對象時,titlepage字段甚至沒有顯示為字段。 我不明白為什么,因為我感覺自己在以正確的方式創建子文檔。

var mongoose = require('mongoose');
var TitlePage = new mongoose.Schema({
    chair: String,
    director: String, 
    author: String
});
var PlaySchema = new mongoose.Schema({
    name: String, 
    titlepage: TitlePage
});
module.exports = mongoose.model('play', PlaySchema);

嘗試創建兩個不同的架構並引用它。

說保存為title.js

 var mongoose = require('mongoose');
    var TitlePage = new mongoose.Schema({
        chair: String,
        director: String, 
        author: String
    });
    module.exports = mongoose.model('titlePage', TitlePage);

說保存為play.js

 var mongoose = require('mongoose');
    var title = require('./title');
    var PlaySchema = new mongoose.Schema({
        name: String, 
        titlepage: mongoose.Schema.Types.ObjectId,
        ref: 'titlePage',
    });
    module.exports = mongoose.model('play', PlaySchema);

當添加標題的ID時,您將引用標題頁的整個文檔。 這將存儲為id,如果要顯示標題的所有字段,則必須填充它。

假設您使用的是find方法,您將收到的文檔將是

{
 name:'abc',
  titlepage: here mongoid will come
 }

但是當您使用find()。populate([[{path:'titlepage'}])填充時,響應將是

{
 name: 'abc',
 titlePage: {
    chair: 'pqr',
    director: 'xyz',
    author: 'lmn'
             }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM