是否可以保存已填充的文档?
我正在尝试:
var Group = new Db['Group']();
for (var i=0; i<50; i++)
Db.Members.push({ User: { _id: "521014731e27b1b008000002"}, pseudo: 'John' });
Group.save();
架构
var GroupSchemaModel = {
Members: [{
User: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
updated_at: { type: Date, required: true, default: Date.now }
}]
};
我收到错误
{ message: 'Cast to ObjectId failed for value "[object Object]" at path "User"',
name: 'CastError',
type: 'ObjectId',
value: { _id: '521014731e27b1b008000002' },
path: 'User' }
答案 0 :(得分:1)
此:
User: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
告诉mongoose User
字段将是指向另一个集合的ObjectId
类型的引用的集合。
另一方面,你试图在那里插入一个物体:
Db.Members.push({ User: { _id: "521014731e27b1b008000002"}, pseudo: 'John' });
Mongoose尝试将其强制转换为ObjectId
并失败。这与pseudo
字段不在组模式中的事实不同。
请改为尝试:
Db.Members.push({User: mongoose.Types.ObjectId("521014731e27b1b008000002"), updated_at: whatever});