javascript - Mongoose + Mongodb User.update 不工作
问题描述
我要做的是创建一个新集合,并将该集合推送到特定的 User.collections 数组中。我已经阅读了许多 stackoverflow 帖子,他们都说要使用 User.update() 或 User.findOneAndUpdate()。我也没有运气。我可以创建一个集合并将其保存到 mongo,所以我知道我确实在访问数据库。这是我的代码,如果有人能提供帮助,我将不胜感激。
用户模式
const mongoose = require('mongoose');
const { Schema } = mongoose;
const userSchema = new Schema({
googleID: String,
givenName: String,
familyName: String,
collections: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "collection"
}
]
});
mongoose.model('users', userSchema);
集合架构:
const mongoose = require('mongoose');
const { Schema } = mongoose;
const collectionSchema = new Schema({
type: String,
name: String,
gamesCollected: [
{
id: Number
}
]
});
mongoose.model('collection', collectionSchema);
还有我的路线:
router.get('/get_collection', (req, res) => {
const collection = new Collection({
type: 'SNES',
name: 'First SNES Collection',
gamesCollected: [{ id: 5353 }]
}).save();
User.update({googleID: req.user.googleID}, {$push: {collections: collection}});
});
解决方案
Save不是同步操作,而是异步操作,因此您需要使用它返回的Promise并处理它,一旦完成,然后更新用户模型。这些行中的一些东西:
router.get('/get_collection', async (req, res) => {
let collection = new Collection({
type: 'SNES',
name: 'First SNES Collection',
gamesCollected: [{ id: 5353 }]
})
await collection.save().exec();
await User.update(
{googleID: req.user.googleID},
{$push: {collections: collection._id}}
).exec();
});
推荐阅读
- python - 如何解决 cx_Oracle 连接不工作:ORA-03113
- python - Tfidfvectorizer - 从变换中获取具有权重的特征
- excel - 当只有 1 行数据可见时出现运行时错误
- javascript - 单个画布上的多个 WebGLRenderer
- laravel-5 - 如何执行具有默认输入的变量函数
- javascript - 如何在 Component 中使用 StyledComponents 主题
- python - 如何使用 list_objects_v2 从 S3 获取超过 1000 个对象?
- sh - 如何将命令行参数传递给 kdb 函数
- perl - Perl:正确引用所有特殊字符
- dart - onTap 不适用于 ListWheelScrollView 子项 - Flutter