gpt4 book ai didi

node.js - 如何获取 Mongoose 中的所有嵌套文档对象

转载 作者:太空宇宙 更新时间:2023-11-03 23:41:29 26 4
gpt4 key购买 nike

我是 mongo DB 的新手。我正在使用 MEAN 堆栈开发一个应用程序。在我的后端,我有两个模型 - 功能和项目。

项目架构有一个名为“features”的属性,它是一个功能对象数组。

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

var ProjectSchema = new Schema({
name: {
type: String,
default: '',
trim: true
},
features:{
type: [Schema.ObjectId],
ref: 'Feature'
}
});

/**
* Statics
*/
ProjectSchema.statics.load = function(id, cb) {
this.findOne({
_id: id
})
.populate('features')
.exec(cb);
};

mongoose.model('Project', ProjectSchema);

请注意,我有单独的功能和项目架构文件。我将这两个模式注册为 Mongoose 模型。我还有一个 Controller ,用于导出以下中间件功能的项目:

'use strict';

/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Project = mongoose.model('Project'),
Testcase = mongoose.model('Feature'),
_ = require('lodash');


/**
* Find project by id
*/
exports.project = function(req, res, next, id) {
Project.load(id, function(err, project) {
if (err) return next(err);
if (!project) return next(new Error('Failed to load project ' + id));
console.log(project.features.length);
req.project = project;
next();
});
};

由于我在项目架构的静态加载函数中使用了“.populate('features')”,因此我期望上面项目对象中的功能对象的所有详细信息。但它没有发生,它为 features 属性返回一个空数组。谁能告诉我我在这里缺少什么吗?

最佳答案

Project schema has an attribute called 'features' which is an array of Feature objects.

小心那里。您需要的是与功能文档相对应的 ObjectId 数组。

我认为您需要像这样指定project.features架构:

features: [{type: Schema.ObjectId, ref: 'Feature'}]

只有代码和数据都100%正确时,填充函数才有效,而且很容易出错。您可以发布您正在加载的项目文档的示例数据吗?我们需要确保 features 确实是一个数组,确实包含 ObjectId,而不是字符串或对象等。

关于node.js - 如何获取 Mongoose 中的所有嵌套文档对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23094218/

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