gpt4 book ai didi

node.js - 填充多个级别不起作用

转载 作者:可可西里 更新时间:2023-11-01 10:42:25 25 4
gpt4 key购买 nike

First = new mongoose.Schema({
name: String,
second: {type: Schema.Types.ObjectId, ref: 'Second'},
});

Second = new mongoose.Schema({
name: String,
third: {type: Schema.Types.ObjectId, ref: 'Third'},
});


Third = new mongoose.Schema({
name: String
});

First.find({}).populate({
path: 'Second',
populate: { path: 'Third'}
}).exec(function(err, result) {
console.log(result)
})

第一个填充没问题,但第三个总是null。意思是我得到了这样的东西:

{
name: 1,
second: {
name: 2,
third: null

}}

最佳答案

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

mongoose.connect('mongodb://localhost/test');

var FirstSchema = new mongoose.Schema({
name: String,
second: {type: Schema.Types.ObjectId, ref: 'Second'},
});

var SecondSchema = new mongoose.Schema({
name: String,
third: {type: Schema.Types.ObjectId, ref: 'Third'},
});


var ThirdSchema = new mongoose.Schema({
name: String
});

var First = mongoose.model('First', FirstSchema);
var Second = mongoose.model('Second', SecondSchema);
var Third = mongoose.model('Third', ThirdSchema);

First.remove({}).exec();
Second.remove({}).exec();
Third.remove({}).exec();

var _3 = new Third({name: 'third'});
_3.save(function(err1) {
if (err1) {
throw err1;
}
var _2 = new Second({name: 'second', third: _3.id});
_2.save(function(err2) {
if (err2) {
throw err2;
}
var _1 = new First({name: 'first', second: _2.id});

_1.save(function() {
First.find({}).populate({
path: 'second',
populate: { path: 'third'}
}).exec(function(err, result) {
console.log(result[0]);
});
});
});
});

enter image description here

您的路径是否被分配了错误的值或其他什么?

应该是字段名,不是对象名

关于node.js - 填充多个级别不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36074880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com