【发布时间】:2019-04-09 04:03:16
【问题描述】:
我要做的是创建一个新集合,然后将该集合推送到特定的 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}});
});
【问题讨论】:
标签: javascript mongodb express mongoose mongoose-schema