mongoose不能使用typesstring填充
所以我有这个FacilityPersonnel
模型的字段:
var field = { createdAt: {type: Date, default: Date.now()}, updatedAt: {type: Date, default: Date.now()}, some_id: {type: String}, fooAccessType: { type: String, default: 'SuperAdmin', ref: 'AccessType' }, }
我试图在控制器上使用这个populate
fooAccessType
。
FacilityPersonnel.findOne({_id:req.params.id}) .populate('fooAccessType') .exec(function (err, doc) { if (err) { res.status(500).json(err); return; }; res.status(200).json(doc); })
所有要查询的数据都是可用的,并且当我删除行.populate('fooAccessType')
时查询正在工作,但如果没有,我会返回这个错误:
{ "stack": "Error\n at MongooseError.CastError ...", "message": "Cast to ObjectId failed for value \"SuperAdmin\" at path \"_id\"", "name": "CastError", "kind": "ObjectId", "value": "SuperAdmin", "path": "_id" }
这是为什么? 谢谢。
目前,只有引用另一个集合的_id
的ObjectId
值可以用作refs
。
这里是一个讨论https://github.com/Automattic/mongoose/issues/2562
不过,这可能是未来的一个增强。
实际上,不需要在populate
字段中添加default
值,只需定义fooAccessType
如下
fooAccessType: { type: String, ref: 'AccessType' },
为population
FacilityPersonnel.findOne({_id:req.params.id}) .populate('fooAccessType') .exec(
ObjectID
用于population
, ObjectId
是一个12字节的BSONtypes,使用下面的构造:
表示自Unix纪元以来秒数的4字节值,
一个3字节的机器标识符,
一个2字节的进程ID,和
一个3字节的计数器,从一个随机值开始。
所以SuperAdmin
不是一个正确的ObjectID
。 您可以使用UUID作为ObjectID
的默认值
var uuid = require('node-uuid'); // ... fooAccessType: { type: String, default: uuid.v1, ref: 'AccessType' },
但是,上面的代码很奇怪, fooAccesType
是对AccessType
文档的引用。
当试图保存field
文档时,应先保存AccessType
,然后从保存的AccessType
获取ObjectID
并将其分配给fooAccessType
,最后保存新的field
文档。
var access = new AccessType({}); access.save(function(err){ if (err) // error handling else { facilityperson.fooAccessType = access._id; facilityperson.save(function(err) { }); } });
为population
FacilityPersonnel.findOne({_id:req.params.id}) .populate('fooAccessType') .exec(