I am trying to make only one user with custom _id and other's with default value.
const userSchema = new mongoose.Schema({
_id: { type: String, default: mongoose.Types.ObjectId() },
password: String,
fName: String,
lName: String,
email: { type: String, unique: true, lowercase: true },
blogs: [blogSchema],
followers: Array,
followings: Array,
darkMode: Boolean,
});
Custom id works, user has _id as string.
enter image description here
But the others value type is also a string not ObjectId.
enter image description here
Is it way to convert this default _id to ObjectId?
Or will there be any problem if I left it as a string?
Related
I am currently trying to track which users like a certain post and based on that information there will be a 'liked' functionality on the post if the user already liked it. How would I go about this with these two current mongoose Schemas that I have?
User.js
const mongoose = require('mongoose')
const userSchema = mongoose.Schema({
username: String,
name: String,
email: String,
passwordHash: String,
dateOfBirth: Date,
location: String,
addictions: Array,
groups: Array,
biography: String,
posts: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}
],
profileImageURL: String,
following: Number,
followers: Number
})
userSchema.set('toJSON', {
transform: (document, returnedObject) => {
returnedObject.id = returnedObject._id.toString()
delete returnedObject.__v
// the passwordHash should not be revealed
delete returnedObject.passwordHash
}
})
const User = mongoose.model('User', userSchema)
module.exports = User
post.js
const mongoose = require('mongoose')
const postSchema = new mongoose.Schema({
text: {
type: String,
required: true
},
images: Array,
video: String,
gif: String,
date: Date,
tags: String,
likes: Number,
comments: Number,
shares: Number,
owner: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String,
replies: {
type: mongoose.Schema.Types.ObjectId,
ref: "Replies"
},
})
const Post = mongoose.model('Post', postSchema)
module.exports = Post
Should i make a separate schema for likes to achieve this or can it be done with the two schemas i already have defined? Thanks!
This question was asked several times, but despite that, I wasn't able to solve my problem. In my mongoose collection, I store 30 users with the following mongoose schema. I want to implement a newsletter on my site, therefore I want to add the new field:
newsletter: {
type: Boolean,
default: true
},
My question is: How can I add newsletter false/true to every user?
I found that, but it didn't work.
User.updateMany({}, [{ $set: { newsletter: false }}])
My Schema:
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
date: { type: Date, default: Date.now },
token: { type: String, required: true }
});
const User = mongoose.model('User', UserSchema);
module.exports = User;
Adding to the schema "newsletter" does solve the problem for new users, but doesn't add the field to the already existing ones.
My database contains two different collections I have "groups" and I have "users". Each group has a field "participants" which is an array that contains either users or guests. Guests unlike users are stored in the group (since they're bound to the specific group).
I use the "participant" schema as an abstraction object between users/guests and the group, this way I can give different users different privileges.
Now to my problem. What I want is the "participant" schema to work for both users and guests which it would if guests would have been its own collection. However, in this case guests belong to the group object and I'm therefore not sure how I'm supposed to reference it. I've tried enum: ["user", "guests"] and enum: ["user", "meetings.guests"] but without any result. I only get the following error:
MissingSchemaError: Schema hasn't been registered for model "guests".. This tells me that I obviously haven't understood how to reference/link subdocuments in the same collection.
Note that I don't want guests to be their own collection
Maybe I can somehow move the "guest" object to "participants.user" but then I would somehow have to tell mongo that it's not an ObjectId anymore but an object?
Group.model.ts
export const ParticipantSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
required: true,
refPath: "participants.userModel"
},
userModel: {
type: String,
required: true,
enum: ["user", "guests"] // How am I supposed to connect the guests as reference? The guests don't have their own collection, they are stored inside the group
},
privilege: {
type: Number,
required: true
}
})
export const GroupSchema = new Schema({
title: {
type: String,
required: true
},
description: {
type: String
},
participants: [ParticipantSchema],
guests: [GuestSchema]
}, {
timestamps: true
})
export default database.model("group", GroupSchema)
User.model.ts
export const UserSchema = new Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: true,
}
}, {
timestamps: true
})
export default database.model("user", UserSchema)
I've been struggling with a weird exception and still confused about it after an hour.
CastError: Cast to ObjectId failed for value "pedrammarandi#gmail.com"
at path "_id" for model "Account"
I'm trying to retrieve an Account via email address. Here is my query
export async function getPendingRecipients(user_id, email_address) {
const account = await Account
.find({email: email_address})
.exec();
return true;
}
This is my Schema object
const userGmailSchema = new Schema({
id: {
type: String,
unique: true
},
displayName: String,
image: Object,
accessToken: String,
user: {
type: Schema.Types.ObjectId,
ref: 'User'
},
refreshToken: {
type: String,
default: null
},
email: {
type: String,
unique: true
},
emails: [
{
type: Schema.Types.ObjectId,
ref: 'Emails'
}
]
});
I'm not sure, but I guess the problem is you wrote an id field.
In MongoDB, the "primary key" is _id field, which is an ObjectId object (actually it's a 12-byte-value), and in mongoose, id is a virtual getter of _id, easily said, id is an alias of _id.
(A little different is that, _id returns ObjectId, id returns String version of _id.)
By default, mongoose manage _id field automatically, so commonly we should not write anything about id in schema.
If your id is for something like primary key ID in SQL DB, just remove it from mongoose schema. If it's means something else in your app, try to add an option:
const userGmailSchema = new Schema({
// your schemas here
},
{
{ id: false } // disable the virtual getter
})
or rename it.
http://mongoosejs.com/docs/guide.html#id
Hope this helps.
I have two Mongo schemas defined as follows:
var userSchema = new mongoose.Schema({
email: String,
password: String, //hash created from password
firstName: String,
lastName: String,
comment:{userComment:String,adminComment:String},
postalAddress: String,
city: String,
state: String,
country: String,
institution: String,
privilege: {type: String, enum:['normal','chair','admin']},
status: {type:String, enum: ['granted','removed','pending']},
myConference:[{type:Schema.Types.ObjectId,ref:'Conference'}],
mySubmission:[{type:Schema.Types.ObjectId,ref:'Submission'}]
});
var conferenceSchema = new mongoose.Schema({
conferenceTitle: {type:String},
conferenceDescription: String,
conferenceStartDate:{type:Date, default: Date.now},
submissionEndDate:{type:Date},
reviewEndDate:{type:Date},
**conferenceMembers:[{type:Schema.Types.ObjectId,ref:'User'}]**,
conferenceSubmissions:[{type:Schema.Types.ObjectId,ref:'Submission'}],
createdBy:{type:Schema.Types.ObjectId,ref:'User'},
//chairMembers:[{type:Schema.Types.ObjectId,ref:'User'}],
department:String
});
Requirement: I want to fetch all the Conference objects which match a certain _id i.e. unique for each 'User' schema object.
conferenceMembers is an array of 'User' objects
What I did:
It's a POST:
var userId=req.body.userId
**Conference.find({userId: {$in: [Conference.conferenceMembers]}},function(err,conf){**
if(err){
return res.send(500, err);
}
return res.send(200,conf);
But, the filter doesn't seem to work here, I tried with $elemMatch as well but no luck.
To fetch all the documents which has specific userId in conferenceMembers, you can do this:
Conference.find({conferenceMembers : userId}).exec(function(err,conf){...});
if you want to populate the users too you can use mongoose populate.
Conference.find({conferenceMembers : userId}).populate('conferenceMembers').exec(function(err,conf){...});