It looks like it doesn’t like how I set the nested schema?
User Schema
const mongoose = require("mongoose");
const twitchSchema = mongoose.Schema(
{
id: Number,
login: String,
display_name: String,
type: String,
broadcaster_type: String,
description: String,
profile_image_url: String,
offline_image_url: String,
view_count: Number,
email: String,
created_at: String,
provider: String,
accessToken: String,
refreshToken: String,
},
{ _id: false }
);
const userSchema = new mongoose.Schema({
provider: {
youtube: {},
twitch: twitchSchema,
},
});
module.exports = mongoose.model("User", userSchema);
This is how I create a new document
const userModels = new UserModels();
userModels.provider[profile.provider].login = profile.login;
const result = await userModels.save()
5
Answers
You are using
mongoose.Schema
incorrect. This is called embeded documents in mongodb. You can define schema like following:Try defining user schema like this :-
There are a couple issues:
youtube: {},
is not a valid schema type, should beyoutube: Object
for example, or define a schema for it! (see my next bullet)The above results in the following document:
If I were you I would do something like this
Define Schemas
After this when I want to save the
user
andtwitch
value. I would doI didn’t test the code exactly, so there might be few things to fix here and there but this would be the general concept I would follow
You should always add the error you are getting in your question. I have tried your code and got undefined reference error:
So the problem is while setting the login field in the user model. You should tweak your userSchema like this:
Please see mongoose documentation here.
Now if you run the below driver code it is able to create the record in mongo.
See logs below: