gpt4 book ai didi

mongodb - 如何保存填充的文档?

转载 作者:行者123 更新时间:2023-12-02 03:11:28 24 4
gpt4 key购买 nike

是否可以保存填充的文档?

我正在尝试做:

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' }

最佳答案

这个:

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});

关于mongodb - 如何保存填充的文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18422793/

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