2017-06-15 50 views
1

我有一個mongoDB數據庫,它是使用只使用node.js mongoDB驅動程序而不使用mongoose的腳本生成的。稍後,在應用程序中,我想使用貓鼬來加載文檔並自動填充引用;然而,這隻有返回nullmongoose#populate在數組中嵌套對象返回null

想象一下一個任務,其中包含每個都有一個標題和一個指定人員的子項目。在這種情況下,被分配的人是我想要填充的引用,因此引用位於任務模式中的數組內的對象中。

下面的代碼(需要npm install mongodb mongoose)重現問題(注意,它破壞了一個名爲test如果你有一個已經是本地數據庫):

const mongodb = require('mongodb'); 
const mongoose = require('mongoose'); 
const Schema = mongoose.Schema; 

(async() => { 
    // Step 1: Insert data. This is done using the mongodb driver without mongoose. 
    const db = await mongodb.MongoClient.connect('mongodb://localhost/test'); 
    await db.dropDatabase(); 
    await db.collection('persons').insertOne({ name: 'Joe' }); 

    const joe = await db.collection('persons').findOne({ name: 'Joe' }); 
    await db.collection('tasks').insertOne({ items: [{ title: 'Test', person: joe._id }] }); 

    await db.close(); 

    // ================ 
    // Step 2: Create the schemas and models. 
    const PersonSchema = new Schema({ 
     name: String, 
    }); 
    const Person = mongoose.model('Person', PersonSchema); 

    const TaskSchema = new Schema({ 
     items: [{ 
      title: String, 
      person: { type: Schema.Types.ObjectId, ref: 'Person' }, 
     }], 
    }); 
    const Task = mongoose.model('Task', TaskSchema); 

    // ================ 
    // Step 3: Try to query the task and have it populated. 
    mongoose.connect('mongodb://localhost/test'); 
    mongoose.Promise = Promise; 

    const myTask = await Task.findOne({}).populate('items.person'); 

    // :-(Unfortunately this prints only 
    // { _id: "594283a5957e327d4896d135", items: [ { title: 'Test', person: null } ] } 
    console.log(JSON.stringify(myTask, null, 4)); 

    mongoose.connection.close(); 
})(); 

預期輸出將

{ _id: "594283a5957e327d4896d135", items: [ { title: 'Test', person: { _id: "594283a5957e327d4896d134", name: "Joe" } } ] } 

我已經驗證了兩個_id實際上使用mongo shell匹配:

> db.persons.find({}) 
{ "_id" : ObjectId("594283a5957e327d4896d134"), "name" : "Joe" } 
> db.tasks.find({}) 
{ "_id" : ObjectId("594283a5957e327d4896d135"), "items" : [ { "title" : "Test", "person" : ObjectId("594283a5957e327d4896d134") } ] } 

我在做什麼錯誤時試圖填充person?我正在使用貓鼬4.10.6和mongodb 2.2.28。

+0

*注*:在'populate'調用之後添加'.exec()'也不起作用,也不會使用回調而不是'await'。 –

+0

現在也作爲[問題#5367](https://github.com/Automattic/mongoose/issues/5367)在貓鼬上開啓。 –

回答

0

這個問題的答案的問題在於這樣一個事實:集合名稱貓鼬自動從模型Personpeople而不是persons推斷。

的問題可以通過在第一部分寫people收集或迫使貓鼬使用集合名稱persons解決:反正

const Person = mongoose.model('Person', PersonSchema, 'persons'); 

貓鼬計劃取消集合名稱多元化,見Github#1350。