mongoose index creation issue after drop collection - node.js

I had created one index on the collection and it was created. But after the drop that collection and when I restarted node server then collection are created again but the index isn't can anybody suggest what is the cause?
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const validator = require('validator')
const FeatureSchema = new Schema({
name:{
type: String,
trim: true,
required: "Please enter a feature name!"
},
slug: String,
description: {
type: String,
trim: true
},
author: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: 'You must supply an author'
},
productID: {
type: mongoose.Schema.ObjectId,
ref: 'Product',
required: 'You must supply an product'
}
},{
timestamps: {
createdAt: 'createdDate',
updatedAt: 'updatedDate'
}
});
// Define our indexes
FeatureSchema.index({
name: 'text'
});
module.exports = mongoose.model('Feature', FeatureSchema);

try to stop mongodb service and restart it again.

Related

How to create a dynamic nested mongoose document with the same schema on multiple levels

Before everyone tells me I can't call a const before initializing, I do know that.
But I think this is the simplest way to render the concept I have in mind, (where any subdocument within the replies array also has the same schema as the parent, and documents within the replies array of those subdocuments also having the same schema). I would really appreciate anyone's input.
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
var commentSchema = new mongoose.Schema({
content: String,
createdAt: {
type: Date,
default: Date.now
},
score: {
type: Number,
default: 1
},
username: {
type: String,
lowercase: true
},
parent: {
type: Schema.Types.ObjectId,
ref: 'comment'
},
replyingTo: String,
replies: [commentSchema]
});
module.exports = mongoose.model("comment", commentSchema);
Since a const can't be called before initialization, to fix this issue the parent schema should be called on the children array after initialization the code below:
commentSchema.add({ replies: [commentSchema] })
The final result should look like this:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const commentSchema = new mongoose.Schema({
content: String,
createdAt: {
type: Date,
default: Date.now
},
score: {
type: Number,
default: 1
},
username: {
type: String,
lowercase: true
},
parent: {
type: Schema.Types.ObjectId,
ref: 'comment'
},
replyingTo: String,
});
commentSchema.add({ replies: [commentSchema] })

Is there a way to pass user Id to schema?

I have a user schema and an exam schema, i wanted to pass the id of the user to the schema of the exam
const ExamSchema = new mongoose.Schema({
-----> _id: [{
class: { type: String, required: true },
module: { type: Number,required:true },
date: {type: Date, required: true }
}]
Where it says _id - i wanted it to be the id of the user! Should i do it like this or add the exams schema on the user schema? Like this?
const UserSchema = new mongoose.Schema({
username: { type: String, require: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
active: { type: Boolean, default: true },
exam: [{
class: { type: String, required: true },
module: { type: Number,required:true },
date: {type: Date, required: true }
}]
});
Check Mongoose "Populate"
https://mongoosejs.com/docs/populate.html
A part from the docs,
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const personSchema = Schema({
_id: Schema.Types.ObjectId,
name: String,
age: Number,
stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
const storySchema = Schema({
author: { type: Schema.Types.ObjectId, ref: 'Person' },
title: String,
fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
const Story = mongoose.model('Story', storySchema);
const Person = mongoose.model('Person', personSchema);
So far we've created two Models. Our Person model has its stories field set to an array of ObjectIds. The ref option is what tells Mongoose which model to use during population, in our case the Story model. All _ids we store here must be document _ids from the Story model.
In your case just make a user_id in Exam Schema and refer to id of User Schema
const ExamSchema = new mongoose.Schema({
user_id: {type: Schema.Types.ObjectId, ref: 'User' },
class: { type: String, required: true },
module: { type: Number,required:true },
date: {type: Date, required: true }
})

Mongoose - Reference a field from another table

I have two tables: Post and User and I want to reference the User name in the Post table.
I can reference the ID but I also need the name.
User model:
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
})
module.exports = mongoose.model("User", userSchema)
Post model:
const { ObjectId } = mongoose.Schema.Types
const postSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
author: {
type: ObjectId,
ref: "User",
},
})
module.exports = mongoose.model("Post", postSchema)
In the doc they said:
Note: ObjectId, Number, String, and Buffer are valid for use as refs.
However, you should use ObjectId unless you are an advanced user and
have a good reason for doing so.
However I couldn't find an example on how I can do this.

Is it possible to reference a mongoose Schema in another mongoose schema without the ObjectId property

I have the two mongoose schemas where one schema reference the other. For example I have
const loginsSchema = new mongoose.Schema({
displayName:{
type:String,
required:true,
},
serviceId:{
required:true,
type:String,
unique:true
}
})
const logins = mongoose.model('logins',loginsSchema);
module.exports = logins;
const usersSchema = new mongoose.Schema({
userName: {
type: String,
required: true,
},
email: {
type: String,
unique: true,
},
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'logins',
unique: true
}
})
What I would like to do is to create a new schema and reference the userSchema in it but not with the objectid. I would like to use the email property.
For Example
const usersSchema = new mongoose.Schema({
name1: {
type: String,
required: true,
},
name2: {
type: String,
unique: true,
},
emailref: {
/// reference the username schema with the email property instead of the objectId
}
})
How can I do that in mongoose?

mongoose populate field without ref option

I have 3 schema:
var User1Schema = new Schema({
name: {type:String , trim: true, required: true },
status: {type:Number, required: true, default:1}
},{collection:"user_1"});
,
var User2Schema = new Schema({
name: {type:String , trim: true, required: true },
email: {type: String, required: true, index: {unique: true} },
status: {type:Number, required: true, default:1}
},{collection:"user_2"});
and
var ConversationSchema = new Schema( {
participants: [{user:{type: ObjectId, required: true}],
creator: {type: ObjectId, required: true},
status: { type:Number, required: true, default:1 }
}, { collection:"conversation" } );
In ConversationSchema I have creator field whic has now ref option, because it can be type of User1Schema or User2Schema.
How can I populate creator field using mongoose
Conversation.find().populate('creator', null, 'User2').exec(callback)
The docs aren't clear. Will update soon.
Also, the syntax for this will be simpler in v3.6.
As of 27th March 2019 the way to do so is:
1) Setting the field you want to populate as a ObjectId without providing a ref.
var eventSchema = new Schema({
name: String,
// The id of the corresponding conversation
// Notice there's no ref here!
conversation: ObjectId
});
2) While making the query pass the model for the schema along with the query:
Event.
find().
populate({ path: 'conversation', model: Conversation }).
exec(function(error, docs) { /* ... */ });
REF: https://mongoosejs.com/docs/populate.html#cross-db-populate

Resources