Mongoose schema update is not pick it up by Mongodb database - javascript

I've my db already created where I have the following schema:
const ProjectSchema = new mongoose.Schema({
name: { type: String },
description: { type: String },
client: {
type: mongoose.Schema.Types.ObjectId,
ref: 'client'
},
group: {
type: mongoose.Schema.Types.ObjectId,
ref: 'project_group'
}
});
I need to change the schema to
const ProjectSchema = new mongoose.Schema({
name: { type: String, unique: true, required: true },
description: { type: String },
client: {
type: mongoose.Schema.Types.ObjectId,
ref: 'client'
},
group: {
type: mongoose.Schema.Types.ObjectId,
ref: 'project_group'
}
});
because we need to force name to be unique and not null. After change this definition, I see that the db still saving documents with the same name value. My question is, how can I apply any change I've done in my schema? and, how can I do that automatically without doing this manually?
Regards

You most likely need to index that field so it can be quickly searched. Then also restart your server, if you haven't already. It's easy to do if you have MongoDB Compass (the official MongoDB GUI), or you can read this doc.
https://docs.mongodb.com/manual/core/index-single/#create-an-index-on-an-embedded-field

Related

ObjectIDs in other collections without getting duplicate key error

I am getting the following error when trying to create a document in a collection.
MongoServerError: E11000 duplicate key error collection: stock-trading-system-db.trades index: user_id_1 dup key: { user_id: ObjectId('6266de71b90b594dab9037f3') }
Here is my schema:
const tradeSchema = new mongoose.Schema({
user_id: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
stock_id: {
type: Schema.Types.ObjectId,
ref: 'Stock',
required: true
},
stock_amount: {
type: Number,
required: true
},
stock_value: {
type: Number,
required: true
},
time_of_trade: {
type: Date,
required: true,
default: new Date()
},
trade_status: {
type: String,
enum: ['Approved', 'Declined', 'Pending'],
required: true,
default: 'Pending'
}
}, { collection: 'trades' })
I don't want user_id and stock_id to be unique, i just want it to check that those ObjectIDs exist in their respective collections before making the trade document. How do i achieve this?
It looks like a collection saves the schema that is defined in mongoose, and even if you change the schema, the unique values will stay the same inside the collection.
So even though i had removed
unique: true;
from my mongoose schema, it hadn't removed this from the collection in my DB.
Therefore the solution to this is to delete the collection and recreate it.

Mongoose Virtual reference between two ObjectIds

I know it is possible to create a virtual reference using a local _id to a foreign ObjectId, but is it possible to use a local ObjectId to a foreign ObjectId?
I'm trying to figure out if I have a bug somewhere or if this is not possible because it's not working.
const Post = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user',
},
text: {
type: String,
}
})
const ProfileSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user',
},
bio: {
type: String,
max: 500,
}
});
ProfileSchema.virtual('posts', {
ref: 'Post',
localField: 'user',
foreignField: 'user',
});
// query
const profile = await Profile.findOne({
user: req.user.id,
}).populate('posts')
Yes it is possible, but you need to add { toJSON: { virtuals: true } } to the Schema.
const ProfileSchema = new mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user',
},
bio: {
type: String,
max: 500,
},
},
{
toJSON: { virtuals: true },
}
);
From docs:
Keep in mind that virtuals are not included in toJSON() output by default. If you want populate virtuals to show up when using functions that rely on JSON.stringify(), like Express' res.json() function, set the virtuals: true option on your schema's toJSON options.
https://mongoosejs.com/docs/populate.html#populate-virtuals

User, post, and comment model in mongoose

I am making a forum app that is quite similar to Reddit. I am using mongoose here for schema design. I have some doubts regarding models that I have- User, Post and Comment.
Does the schema look all right of all the models?
In User, I want to show the friends on the user profile. Like when you go to his profile, there will be like Friends(200), and when I click the friend list will appear(like Facebook, then on clicking you can access friends' profiles). I haven't created Friend schema, but does it needed actually?
Question about comments. So far, I have the basic comment schema. What happens to the threaded comments or replies. How do I store them?
All the models that I have currently:
const userSchema = new Schema(
{
username: { type: String, required: true },
email: { type: String, reuired: true },
password: { type: String, required: true },
country: { type: String, required: true },
friends: [{ type: Schema.Types.ObjectId, ref: "Friend" }], // is it needed?
posts: [{ type: Schema.Types.ObjectId, ref: "Post" }],
},
{ timestamps: true }
)
const postSchema = new Schema(
{
title: { type: String, required: true },
description: { type: String, required: true },
user: { type: Schema.Types.ObjectId, ref: "User" },
slug: { type: String, slug: "title" },
upvotes: { type: Number },
downvotes: { type: Number },
city: { type: String }, // post will have a tag by the city like NewYork, LA etc.
},
{ timestamps: true }
)
const commentSchema = new Schema(
{
comment: { type: String, required: true },
post: { type: Schema.Types.ObjectId, ref: "Post"},
user: { type: Schema.Types.ObjectId, ref: "User"},
upvotes: { type: Number },
downvotes: { type: Number }
},
{ timestamps: true }
)
For the Second Question you don't need friend schema since friend is also a user.
For the first question, Why do intend to store all the posts of a user inside the User object as a list of posts, this would mean fetching 100s of posts even when something basic like username or email is required. Instead, you can place user_id in the Post Schema, helping to identify posts from a particular User.

Node mongodb stores data as string instead of an object

I have two same functions, first saves some stuff and also saves ref to productId and second saves another stuff and saves ref to productId too. The problem is first writes ref to poductId as object and everything is ok but second function saves ref as string and in mongodb i see ObjectId but when im trying to display data on screen i cant access into object i have only string with ID of refer. Any ideas?
first model which is ok
const mongoose = require('mongoose')
const dishPositionsSchema = mongoose.Schema({
productId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Products'
},
dishId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Dishes'
},
weight: {
type: Number,
required: true
}
})
module.exports = mongoose.model('DishPositions', dishPositionsSchema)
and second which stores only strings instead of objects
const mongoose = require('mongoose')
const diaryPositionsSchema = mongoose.Schema({
productId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Products'
},
dishId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Dishes'
},
weight: {
type: Number,
required: true,
required: true
},
timeOfEatingId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'TimeOfEating'
},
date: {
type: String,
required: true
}
})
module.exports = mongoose.model('DiaryPositions', diaryPositionsSchema)
I know where i did mistake... i didnt write populate('productId')... everything is fine now thanks!

searching for an array in a schema by id

const FormFieldsSchema = new Schema({
formName: {
type: String,
required: true
},
fields: [
{
fieldLabel: {
type: String,
required: true
},
inputData: [{
type: mongoose.Schema.ObjectId,
ref: "UserData"
}]
}
]
});
Hi guys, I have a schema in which fields is an array, now for every array item I have an _id property, I wish to find that array and update it, but I can't manage to do it,
I tried findByIdAndUpdate, but it didnt work, also tried parent.inputData.id(_id); no luck yet, any ideas?
Convert the content of your array into a separate model, then you can query the model directly.
running findByIdAndUpdate on FormFieldsSchema fill search for the _id of FormFields not the content of fields array.
const FieldSchema = new Schema({
fieldLabel: {
type: String,
required: true
},
inputData: [{
type: mongoose.Schema.ObjectId,
ref: "UserData"
}]
})
and change field into fields: [FieldSchema]
also, don't forget to export FieldSchema as a model.

Categories

Resources