gpt4 book ai didi

javascript - 在 MongooseJS 中填充子文档数组

转载 作者:行者123 更新时间:2023-11-30 07:24:23 25 4
gpt4 key购买 nike

我很难尝试用 MongooseJS 填充子文档数组。有人可以帮忙吗?

这是 user.js:

var mongoose = require("mongoose");

var userSchema = new mongoose.Schema({
name: {
type: String
},
positions: {
type: [mongoose.Schema.ObjectId],
ref: 'position'
}
});

userSchema.statics.getUserByID = function (id, callback){
return this.findOne({_id: id}).populate('positions').exec(callback);
};

var user = mongoose.model('user', userSchema);

module.exports = user;

这是 position.js

var mongoose = require("mongoose");

var positionSchema = new mongoose.Schema({
modifiedDate: {
type: Date
},
location: {
type: [Number],
index: '2d'
}
});

var position = mongoose.model('position', positionSchema);

module.exports = position;

调用 getUserByID 时,用户架构的位置数组未被填充。我在这里遗漏了什么明显的东西吗?

编辑

根据下面的回答,我将我的用户架构更改为:

var mongoose = require("mongoose");

var userSchema = new mongoose.Schema({
name: {
type: String
},
positions: [{
type: mongoose.Schema.ObjectId,
ref: 'position'
}]
});

userSchema.statics.getUserByID = function (id, callback){
return this.findOne({_id: id}).populate('positions').exec(callback);
};

var user = mongoose.model('user', userSchema);

module.exports = user;

我还从位置模式中删除了 location 属性,以防那里发生奇怪的事情。

我尝试过的任何事情似乎都没有任何不同。

这是当前保存在 users 集合中的内容:

{
"__v": 1,
"_id": {
"$oid": "531f8ab89938130200433ef8"
},
"modifiedDate": {
"$date": "2014-03-11T22:14:43.174Z"
},
"name": "Josh",
"positions": [
{
"$oid": "531f8ad39938130200433efa"
}
]
}

这是 positions 集合中的内容:

{
"modifiedDate": {
"$date": "2014-03-11T22:14:43.163Z"
},
"_id": {
"$oid": "531f8ad39938130200433efa"
},
"__v": 0
}

作为引用,我在我的 package.json 文件中使用了 "mongoose": "^3.8.8"

我真的被这个难住了,任何帮助将不胜感激。

最佳答案

您在用户模式中犯了一个小而重要的拼写错误 - position 字段的类型不应设置为 ObjectId 数组。您可能想要的是这个架构:

var userSchema = new mongoose.Schema({
name: {
type: String
},
positions: [{
type: mongoose.Schema.ObjectId,
ref: 'position'
}]
});

关于javascript - 在 MongooseJS 中填充子文档数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22260048/

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