$inc not working for my mongo database (on localhost) - node.js

This should be a simple problem. I've formatted my 'update' exactly how it is on mongo's documentation, as you can see:
Message.update(
{ id: messageID },
{ $inc: { votes: 1 } }
);
I am trying to increase 'votes' by 1. Yet it is not changing. Here is my schema file:
var mongoose = require('mongoose');
var MessageSchema = new mongoose.Schema({
room: {
type: String,
required: true
},
timestamp: {
type: Object,
required: true
},
votes: {
type: Number
},
id: {
type: String,
required: true
},
uid: {
type: String,
required: true
},
parent: {
type: String,
required: true
},
text: {
type: String,
required: true
}
});
module.exports = mongoose.model('messages', MessageSchema);
The input 'messageID' is correct, as the 'find' method works perfectly well with this table.

Try with findByIdAndUpdate instead of update . Hope it works
Message.findByIdAndUpdate(messageID ,{ $inc: { votes: 1 }},function(err, response) {
res.send(response);
});

Related

How to receive information from a model inside an array in another model? (mongoose)

I have a "cart" model, and within my "order" model, I would like to have an array that receives the information sent by "cart" stored in an array. How can I do this through ref?
const mongoose = require('mongoose');
const CartSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
},
note: {
type: String,
required: true,
},
price: {
type: Number,
required: false,
},
createdAt: {
type: Date,
default: Date.now,
}
},
{ timestamps: true }
);
module.exports = mongoose.model("Cart", CartSchema);
order
const mongoose = require('mongoose');
const OrderSchema = new mongoose.Schema(
{
list: {
name: String,
notes: String,
},
totalAmount: {
type: Number,
required: true,
},
payment: {
type: String,
required: true,
},
address: {
type: String,
required: true,
},
addressNote: {
type: String,
required: false,
},
createdAt: {
type: Date,
default: Date.now,
}
},
{ timestamps: true }
);
module.exports = mongoose.model("Order", OrderSchema);
Here in "list" I would like it to be an array that receives cart model information
Can I do this through ref? What would be the best possible way?

Mongoose Query is not fetching match data from multiple table

I am using nodejs,mongodb and mongoose. This query is not fetching match data from user and order table. I have read mongoose docs and alot of other articeles. It's according to it but doesn't fetch match data from tables.
Query code:
const data = await order
.find({ admin_id: req.params.id })
.populate("orderRelate");
console.log(data);
My user and order schema code is:
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema(
{
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
mobile_no: { type: Number, required: true },
profilePic: { type: String, defaut: "" },
owner: { type: Boolean, defaut: false },
},
{ timestamps: true }
);
const orderSchema = new mongoose.Schema(
{
customer_id: { type: String, required: true },
admin_id: { type: String, required: true },
order_type: { type: String, defaut: "normal" },
order_status: { type: String, required: true },
order_price: { type: Number, required: true },
order_address: { type: String, required: true },
order_pickDate: { type: String, required: true },
order_pickTime: { type: String, required: true },
orderRelate: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
},
{ timestamps: true }
);
module.exports = mongoose.model("User", UserSchema);
module.exports = mongoose.model("Order", orderSchema);
Please let me know if anyone know why I am facing this issue.
Thanks
Please try with findById maybe it's work
i don't know how you wrote your middleware function but..
await Order.find({orderRelate: req.user.id})

Mongoose How to sort .populate field

I'm work with an user/articles profile system. I have been using the .populate() to render the posts but I cannot get the articles sorted by the date they were created.
I am using the createdAt variable as the main way of ordering the posts displayed.
For reference:
router.get('/:id', async (req, res) => {
const user = await User.findById(req.params.id, function(error) {
if(error) {
req.flash("error", "something went wrong")
res.redirect("/");
}
}).populate('articles')
res.render('users/show',{
user: user
});
and the article.js:
const ArticleSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
author: {
type: String
},
markdown: {
type: String,
required: true
},
createdAt: {
type: Date,
default: Date.now
},
slug: {
type: String,
required: true,
unique: true
},
sanitizedHtml: {
type: String,
required: true
},
img: {
type: String
},
type:{
type: String
},
user : { type: Schema.Types.ObjectId, ref: 'User' },
}, {timestamps: true});
In advance thank you all for the help.
There is a property called options in populate,
.populate({
path: 'articles',
options: { sort: { createdAt: -1 } }
})

Mongoose(mongoDB) Linking multiple schema's

Im relatively new to MongoDB and Mongoose. Im much used to MySQL so in used to inner joining tables on calls. Ive read a lot that you can link two Mongoose Schemas to achieve the same outcome. How would like like the two schemas together to when I make a call to get a chore by id it'll return the chore and then for the assignedTo & createdBy have the user scheme data for the said userId?
Chore Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ChoreSchema = new Schema({
title: {
type: String,
required: true
},
desc: {
type: String,
required: true
},
time: {
type: Number,
required: true
},
reaccurance: {
type: [{
type: String,
enum: ['Daily', 'Weekly', 'Bi-Weekly', 'Monthly']
}]
},
reward: {
type: Number,
required: true
},
retryDeduction: {
type: Number,
required: false
},
createdDate: {
type: Date,
default: Date.now
},
createdBy: {
type: String,
required: true
},
dueDate: {
type: Date,
required: true
},
status: {
type: [{
type: String,
enum: ['new', 'pending', 'rejected', 'completed', 'pastDue']
}],
default: ['new']
},
retryCount: {
type: Number,
default: 0,
required: false
},
rejectedReason: {
type: String,
required: false
},
familyId: {
type: String,
required: true
},
assignedTo: {
type: String,
required: false,
default: ""
}
});
let Chores = module.exports = mongoose.model('Chores', ChoreSchema);
module.exports.get = function (callback, limit) {
Chores.find(callback).limit(limit);
};
User Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
role: {
type: [{
type: String,
enum: ['Adult', 'Child']
}]
},
birthday: {
type: String,
required: false
},
familyId: {
type: String,
required: true
},
balance: {
type: Number,
required: true,
default: 0.00
}
});
let Users = module.exports = mongoose.model('Users', UserSchema);
module.exports.get = function (callback, limit) {
Users.find(callback).limit(limit);
};
Im trying to link ChoreSchema.createdBy & ChoreScheme.assignedTo by UserSchema._id
How I make the call in Node.js:
exports.index = function(req, res) {
Chore.get(function(err, chore) {
if (err)
res.send(err);
res.json({
message: 'Chore List',
data: chore
});
});
};
Mongoose has a more powerful alternative called populate(),
which lets you reference documents in other collections.
https://mongoosejs.com/docs/populate.html
Here is how you can link ChoreSchema.createdBy and ChoreScheme.assignedTo by UserSchema._id
var mongoose = require('mongoose');
const { Schema, Types } = mongoose;
var UserSchema = new Schema({
firstName: { type: String, required: true },
...
})
var ChoreSchema = new Schema({
title: { type: String, required: true },
...
//The ref option is what tells Mongoose which model to use during population
assignedTo: { type: Types.ObjectId, ref: 'Users' },
createdBy: { type: Types.ObjectId, ref: 'Users' },
})
let Chores = mongoose.model('Chores', ChoreSchema);
let Users = mongoose.model('Users', UserSchema);
Then in your express route handler you can populate assignedTo & createdBy like this
router.get('/chores/:id', function (req, res) {
const choreId = req.params.id;
Chores.find({ _id: choreId })
.populate('createdBy') // populate createdBy
.populate('assignedTo') // populate assignedTo
.exec(function (err, chore) {
if(err) {
return res.send(err)
}
res.json({ message: 'Chore List', data: chore });
});
})

How can I fetch data from more than one collections in Mongo using mongoose

How I can display details data of a profile when those data stored in more than one collections
tried this link
const profile = await userKushala
.find({_id: '5cd407c741f9e7373f10362c'})
.populate({
path: 'settingId',
populate : {
path : 'specialty',
populate : {
path: 'hospital_attached'
}
}
})
// First Collection(Basic Info.)
const userRegisterSchema = new Schema({
userType: {
type: String,
required: true
},
mobile: {
type: Number,
required: true,
unique: true
},
userId: {
type: String,
required: true
},
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
age: {
type: Number,
required: true
},
gender: {
type: String,
required: true
},
settingId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'providerSetting'
}
})
// Second Collection(Detailed Info.)
const serviceProfileUpdate = new Schema({
specialty :[{
type: mongoose.Schema.Types.ObjectId,
ref: 'specialtyMasterCsv'
}],
category: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'categoryMasterCsv'
}],
subscriptionPlan: {
type: mongoose.Schema.Types.ObjectId,
ref: 'planMasterCsv'
},
medicine: {
type : mongoose.Schema.Types.ObjectId,
ref: 'kushalaUser'
}
})
//Data in Mongo
{
"_id":{
"$oid":"5cd93ea6bd96e43664f49bf3"
},
"specialty":[
{
"$oid":"5cda85f26ffe60259a75ba17"
},
{
"$oid":"5cda85f26ffe60259a75ba18"
}
],
"category":[
{
"$oid":"5cda85f26ffe60259a75ba17"
},
{
"$oid":"5cda85f26ffe60259a75ba18"
}
],
"subscriptionPlan":{
"$oid":"5cda85f26ffe60259a75ba17"
},
"medicine":{
"$oid":"5cd407c741f9e7373f10362c"
},
"__v":{
"$numberInt":"0"
}
}
Expected Result will be from all the collections data should fetch but with the code I have it's giving the result till specialty but after that it's printing only ObjectID
This is what I have done and it's working still if anyone has a better solution, most welcome. Hope it helps someone.
const profile = await userKushala
.find({_id: '5cd407c741f9e7373f10362c'})
.populate({
path: 'settingId',
populate : {
path : 'specialty category subscriptionPlan medicine'
}
})
Try to populate like this:
.populate([
{path:'category',model:'categoryMasterCsv'},
{path:'subscriptionPlan',model:'planMasterCsv'},
{path:'medicine',model:'kushalaUser'}])
This is the method I use daily.

Resources