在MongooseJS中填充子文档的数组
我很难尝试用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
字段的types不应该被设置为ObjectId
数组。 你可能想要的是这个模式:
var userSchema = new mongoose.Schema({ name: { type: String }, positions: [{ type: mongoose.Schema.ObjectId, ref: 'position' }] });
尝试使用“mongoose.Schema.Types.ObjectId”而不是“mongoose.Schema.ObjectId”,前一段时间我有类似的问题。 但我相信,不是你的情况是否有帮助。
我已经没有进一步的转发了。
我已经重组了一切,以便我可以直接查询子文档,而不是依赖于填充方法。