如何将Mongoose对象推入Mongoose对象中的数组?

发布于 2025-02-09 05:20:03 字数 805 浏览 1 评论 0原文

我试图将猫鼬对象推到另一个猫鼬对象内的数组,但是存储在数组中的只是仅推送的猫鼬对象的objectid。

代码是这样的:

user.snippets.push(snippet)

如果我安装了摘要,我会看到整个对象,但是如果我安装了数组用户。Snippets,我只会看到“新ObjectID([Hexadecimal String])”数组。

我已经看到并尝试了像这样的代码

user.updateOne( {
     $push: { snippets: snippet }
} )

,但我无法正常工作,user.snippets.push似乎更自然。

在用户的模型中,我声明了带有

snippets: {
     type: [mongoose.Schema.Types.ObjectId],
     ref: 'Snippet',
     required: false,
     trim: false,
     lowercase: true
}

授权的摘要数组,看起来像一个数组,objectids,但是在片段的模型中,我毫无问题地遇到了此代码:

author: {
     type: mongoose.Schema.Types.ObjectId,
     ref: 'User',
     required: true,
     trim: false,
     lowercase: false
}

我可能不需要小写和修剪,因为它们是对象,但这既不是这里也不是。

I am trying to push a Mongoose object to an array within another Mongoose object, but what is stored in the array is only the ObjectId of the pushed Mongoose object.

The code is like this:

user.snippets.push(snippet)

If I console snippet, I see the whole object, but if I console the array user.snippets I only see an array of "new ObjectId([hexadecimal string])".

I have seen, and tried, code like

user.updateOne( {
     $push: { snippets: snippet }
} )

but I don't get it to work, and user.snippets.push seems more natural.

In the model for User, I declare the snippets array with

snippets: {
     type: [mongoose.Schema.Types.ObjectId],
     ref: 'Snippet',
     required: false,
     trim: false,
     lowercase: true
}

Granted, it looks like an array, of ObjectIds, but in the model for Snippet, I have this code without problems:

author: {
     type: mongoose.Schema.Types.ObjectId,
     ref: 'User',
     required: true,
     trim: false,
     lowercase: false
}

I probably don't need lowercase and trim, as they are objects, but that's neither here nor there.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文