Create like and dislike with nodejs and mongoose - node.js

For my training project, I have to create the controllers for the 'like' and 'dislikes' with the verb post.
Could someone suggest me how to proceed for this?
It's my schema and model:
const mongoose = require('mongoose');
const sauceSchema = mongoose.Schema({
userId: {type: String, required: true},
name: {type: String, required: true},
manufacturer: {type: String, required: true},
description: {type: String, required: true},
mainPepper: {type: String, required: true},
imageUrl: {type: String, required: true},
heat: {type: Number, required: true},
likes: {type: Number, required: true, default:0},
dislikes: {type: Number, required: true, default:0},
usersLiked: {type: [String]},
usersDisliked: {type: [String]},
});
module.exports = mongoose.model('Sauce', sauceSchema);

Related

How to create a mongoose sub model without creating a collection for it

const walletTransactionSchema = new mongoose.Schema({
a: {type: Boolean, required: true},
},
{timestamps: {createdAt: 'created_at', updatedAt: 'updated_at'}});
const walletSchema = new Schema({
b: {type: Boolean, required: true},
transactions: [{type: walletTransactionSchema}],
});
walletSchema.index({'transactions': 1}, {sparse: true});
module.exports.Wallet = mongoose.model('Wallet', walletSchema, 'wallets');
module.exports.WalletTransaction = mongoose.model('WalletTransaction', walletTransactionSchema);
I'm trying to create a model for a subdocument (WalletTransaction) without creating a collection for it. Unfortunately mongoose is automatically creating that collection. How can I prevent that behavior and just define a sub-model without creating a collection. I prefer to organize my schemas by refactoring them instead of just embedding them.
I used to do this without trouble with above definitions. I guess after updating to mongoose 6.0.8 (from 5.13) this is happend.
if you wanna create another model inside a model
You should go with the following approach
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
email: {
type: String,
required: true},
about:{type:String},
password: {type: String, required: true},
friends: [new mongoose.Schema({
user: {type: String}
}, {strict: false})],
profileImage: {type: String, default: "default.jpg"},
userName: {type: String, required: true},
matches: {type: Number, default: 0},
wins: {type: Number, default: 0},
losses: {type: Number, default: 0},
backgroundImage: {type: String, default: "default.jpg"},
resetPasswordToken: {type: String, required: false},
resetPasswordExpires: {type: Date, required: false},
isDeleted: {type: Boolean, default: false},
deletedAt: {type: Date, default: null},
}, {timestamps: true}, {strict: false});
module.exports = mongoose.model('User', userSchema);
Like this I create another model in my User model with name Friends in which each entry has one specific id

reddit comment system how to replicate in mongodb/nodejs

How do I make nested comment replies in MongoDB/mongoose to create a comment system like in reddit nesting. Here are my schemas i created so far:
var CommentSchema = Schema({
body: {type: String},
chapterId: {type: RK, ref: 'Chapter'},
by: {type: RK, ref: 'User'},
}, {timestamps: true});
var UserSchema = new Schema({
name: String,
username: {type:String, unique: true},
profile_pic: String,
password: String,
role:{type: [{
type: String,
enum: ['user', 'admin']
}],
default: ['user']
}
});

Mongodb lookup with two ObjectId

I have a little issue getting lookup to work. It returns an empty array. I use contactId field in Billing Collection. And I use the contact _id created when entry in Contact Collection in mongodb (Can see it in Robomongo). I have few Billings with ContactId corresponding to the _id of few Contacts. Is my syntaxe correct ? Do I miss something ? Thank you for your help.
Below is my lookup syntaxe
Contact.aggregate([
{
$lookup: {
from: "Billing",
localField: "_id",
foreignField: "contactId",
as: "BillingMembership"
}
}
]).exec(function (err, contacts) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(200).json({
message: 'Success',
obj: contacts
});
});
Below is the result I get back from the database.
(4) [Object, Object, Object, Object]
0:Object
BillingMembership:Array(0)
length:0
__proto__:Array(0)
additionalInterests:"MFM/REI"
billingEmail:"john#netdr.net"
cellPhone:6787025500
dateBirth:"1555-02-02T00:00:00.000Z"
firstName:"qtazerqr'efsg"
gogsMbrType:"Resident Applicant"
gogsYearJoined:"20111"
homePhone:6787025500
lastName:"gzaetrsg"
memberSuffix:", DO"
middleName:"fzerqgrre"
notes:"htrfjghdnt"
officeEmail:"john#netdr.net"
officePhone:6787025500
personalEmail:"john#netdr.net"
practiceId:"592e4c1638a494089c50c8c8"
praticeType:"MFM/High Risk"
spFirstNm:"gsertdhy"
spLastNm:"rthytrfgj"
spSuffix:"syhtdrh"
website:"trshdty"
__v:0
_id:"5932db29eb4dfe0de4a8a36d"
__proto__:Object
1:Object
2:Object
3:Object
Mongoose Schema Contact
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');
var schema = new Schema({
firstName: {type: String, required: true},
middleName: {type: String, required: true},
lastName: {type: String, required: true},
dateBirth: {type: Date, required: true},
memberSuffix: {type: String, required: true},
officePhone: {type: Number, required: true},
homePhone: {type: Number, required: true},
cellPhone: {type: Number, required: true},
officeEmail: {type: String, required: true},
billingEmail: {type: String, required: true},
personalEmail: {type: String, required: true},
gogsMbrType: {type: String, required: true},
gogsYearJoined: {type: String, required: true},
spFirstNm: {type: String, required: true},
spLastNm: {type: String, required: true},
spSuffix: {type: String, required: true},
notes: {type: String, required: true},
praticeType: {type: String, required: true},
additionalInterests: {type: String, required: true},
website: {type: String, required: true},
practiceId: {type: Schema.Types.ObjectId, ref: 'Practice'}
});
schema.plugin(mongooseUniqueValidator);
module.exports = mongoose.model('Contact', schema);
Mongoose Schema Billing
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');
var schema = new Schema({
reason: {type: String, required: true},
amount: {type: Number, required: true},
membership: {type: String, required: true},
membershipYear: {type: Schema.Types.ObjectId, ref: 'Membership'},
type: {type: String, required: true},
date: {type: String, required: true},
contactId: {type: Schema.Types.ObjectId, ref: 'Contact'},
conferenceId: {type: Schema.Types.ObjectId, ref: 'Conference'}
});
schema.plugin(mongooseUniqueValidator);
module.exports = mongoose.model('Billing', schema);
Solved. thanks to Veeram.
I used Change your from: "Billing" to from: "billings"

MongoError: can't get query executor with geoNear Mongoose

I am trying to get results from DB using geoNear in Moongose but it is giving "can't get query executor" error.
// Schema
let dealSchema = new Schema({
userId: {type: String, required: true},
images: {type: [String], required: true},
location: {
lng: {type: Number},
lat: {type: Number},
name: {type: String, required: true}
},
description: {type: String, required: false, default: ""},
expiredReports: {type: [String], required: false},
inappropriateReports: {type: [String], required: false},
likes: {type: [String], required: false},
dislikes: {type: [String], required: false},
comments: {type: [commentSchema], required: false},
creationDate: {type: Date, default: new Date()},
updationDate: {type: Date, default: new Date()}
}, {collection: TableName.DEAL});
function getAll(radius) {
var point = {type: "Point", coordinates: [9, 9]};
let distance = parseInt(radius);
if (isNaN(distance)) {
return callback(new Error("Invalid Radius"), null)
}
var geoOptions = {
spherical: true,
maxDistance: distance,
num: 10
};
DealData.geoNear(point, geoOptions, function (err, docs, stats) {
console.log(docs);
}
);
}
This is my model of Mongoose and My code to get data from Database.
geoNear method requires 2dsphere index, after creating that index you'll be able to querying data by coords.
Example:
var mySchema = new mongoose.Schema({
name: {type: String, required: true},
location: {type: [Number], index: '2dsphere'}
});
The first item of the location field is longtitude and the second one is latitude

How to do `$text` search on one collection to get the data from the other collection?

I need to provide search for e-commerce site. In that there is a 4-level menu like this category>>subcategory>>product>>subproduct. I had divided them into 3 schemas like this
category schema
var categorySchema = new mongoose.Schema(
{
"catname": {type: String, required: true},
}
);
mongoose.model('category',categorySchema);
subcategory and product schema
var productSchema = new mongoose.Schema(
{
"catid": {type: mongoose.Schema.Types.ObjectId, ref: 'category'},
"subcatname": {type: String, required: true},
"product":[
{
"productname":{type:String},
}
]
}
);
mongoose.model('product',productSchema);
subproduct schema
var subproductSchema = new mongoose.Schema(
{
"productid": {type: mongoose.Schema.Types.ObjectId, ref: 'products', required: true},
"itemcode": {type: String, required: true},
"itemname": {type: String, required: true/*, index: "text"*/},
"itemdescription": {type: String, required: true},
"itemimgurl": {type: String, required: true},
"mainprice": {type: Number},
"offerprice": {type: Number, required: true},
"unit": {type: String, required: true},
"stock": {type: Number, required: true},
"offertag": {type: String},
"itemprice":[
{
"itemname" :{type: String, required: true},
"unit": {type: String, required: true},
"offerprice": {type: Number, required: true},
"mainprice": {type: Number},
"stock": {type: Number, required: true},
"notify": {type: Number, required: true},
"status": {type: Boolean, required: true},
"itemimgurl": {type: String},
"offertag": {type: String}
}
]
}
);
mongoose.model('subproduct',subproductSchema);
I need to give the subproducts corresponding to the users search, like if the user searches with the catname or subcatname or productname or itemname need to give the related subproducts. How can I achieve this with mongoose?
This is with reference to the question you asked in the comment.
If you want to search for an incomplete query or a word, i will provide a small code, which will help you.
var query = req.body.query; //the string you take for search
var filter = {
$or: [
{subcatname: new RegExp('.*' + query, 'i')},
{productname: new RegExp('.*' + query, 'i')},
//similarly you can put more cases
]
}
subproducts.find(filter, function(err, data){
if(err){console.log(err);}
console.log(data);
});

Resources