I want to fetch all the documents created on D-1 day, i.e. suppose if any record has been created on 4-12-2019 then query should fetch records created on 3-12-2019.
Here is my Model and code:
VENDOR ORDER SCHEMA
const vendorOrderSchema = new mongoose.Schema({
timesOfIndia:{
tradeCopies:{
type:Number,
deafult:0 },
subscriptionCopies:{
type:Number,}
},
economicTimes:{
tradeCopies:{
type:Number,
deafult:0
},
subscriptionCopies:{
type:Number,}
},
mumbaiMirror:{
tradeCopies:{
type:Number,
deafult:0
},
subscriptionCopies:{
type:Number}
},
isApproved:{
type:Boolean,
default:false
},
vOrderCreator:
{
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required:true
}
},
{ timestamps: true }
)
const VendorOrder = mongoose.model('VendorOrder',vendorOrderSchema)
module.exports = VendorOrder
Query:
exports.getOrderById = async (req,res,next) =>{
const vOrderCreator = req.params.id
const vendorOrder = await VendorOrder.find({vOrderCreator,
createdAt: { $gt: new Date(Date.now() - (1000 * 60 * 60 * 24)) }
})
try {
if (!vendorOrder) {
const error = new Error('Could not find post.');
error.statusCode = 404;
throw error;
}
res.status(200).json({ message: 'VendorOrder fetched.', vendorOrder });
} catch (err) {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
}}
POSTMAN RESPONSE
{
"message": "VendorOrder fetched.",
"vendorOrder": [] // getting this empty array
}
Related
How do I delete object from inner schema in mongoose?
I try to delete comments from the Holiday Schema, this is the holiday schema:
const holidaySchema = new mongoose.Schema(
{
comments: [commentSchema],
},
)
const Holiday = mongoose.model("Holiday", holidaySchema);
export default Holiday;
and this is the comments schema:
const commentSchema = new mongoose.Schema(
{
action: { type: String },
time: { type: String },
name: { type: String },
image: { type: String },
content: { type: String },
rating: { type: Number },
},
{
timestamps: true,
}
);
I try to delete a specific comment from the holidaySchema in this way:
holidayRouter.delete(
"/:id/comments/:commentId",
isAuth,
expressAsyncHandler(async (req, res) => {
const holiday = await Holiday.updateOne(
{ _id: req.params.id },
{ $pull: { comments: { _id: req.params.commentId } } }
);
if(holiday){
console.log(holiday);
}
})
);
the console:
and this is not working, do you know what I am doing wrong or what should I do?
thank you
Mongoose converts the object into json, and we can customize that json which is returned.
commentSchema.methods.toJSON = function(){
const commentSchema = this.toObject()
delete commentSchema.name
delete commentSchema.rating
return commentSchema
}
New the JSON which is returned will not have name and rating.
I want to update multiple subdocuments from multiple documents using mongoose.
My current code is:
const ids: any[] = payload.imageIds.map(e => new ObjectId(e));
await this.userModel
.updateMany({ 'images._id': { $in: ids } }, { $inc: { 'images.$.views': 1 } })
.exec();
And part of the schema is:
export const UserSchema = new mongoose.Schema(
{
images: [ImageSchema],
}
const ImageSchema = new mongoose.Schema(
{
views: { type: Number, default: 0 },
},
But this code only updates the last element from the ids arr.
Solved!
For those who encounter the same problem:
const imageIds: ObjectId[] = payload.imageIds.map(e => new ObjectId(e));
const userIds: ObjectId[] = payload.userIds.map(e => new ObjectId(e));
await this.userModel
.updateMany(
{ _id: { $in: userIds } },
{ $inc: { 'images.$[element].views': 1 } },
{
arrayFilters: [
{
'element._id': { $in: imageIds },
},
],
},
)
.exec();
I am using express and mongoose to implement a server/db. I have a working route that gets all the games involving a player by playerID. I am now trying to implement one that can take username instead of playerID.
PLAYER_SCHEMA:
const mongoose = require('mongoose');
const PlayerSchema = mongoose.Schema( {
username: {
type:String,
required:true,
unique:true
},
date_registered: {
type: Date,
default:Date.now
}
});
module.exports = mongoose.model('Player', PlayerSchema);
GAME_SCHEMA:
const mongoose = require('mongoose');
const GameSchema = mongoose.Schema( {
player_1: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Player',
required: true
},
player_2: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Player',
required: true
},
status: {
type:String,
},
hero_1: {
type:String
},
hero_2: {
type:String
},
date_registered: {
type: Date,
default:Date.now
}
});
module.exports = mongoose.model('Game', GameSchema);
Here's what I have to query all games involving a player by playerId:
//GET GAMES INVOLVING PLAYER BY PLAYER_ID
router.get('/player/:playerId', async (req, res) => {
try {
const games = await Game.find({$or:[{ player_1: req.params.playerId }, { player_2: req.params.playerId}]});
console.log(games)
res.json(games);
// weird cuz doesn't throw error if not found, just returns empty list...
}
catch (err) {
res.json({ message: err });
}
});
The following outlines what I want to do, but it doesn't work, for I'm sure many reasons:
I am trying to get the userId from username first, then pass that into a query for the games.
//GET ALL GAMES ASSOCIATED WITH PLAYER BY USERNAME
router.get('/username/:username', async (req, res) => {
try {
const player = await Player.findOne({username:req.params.username});
console.log(player);
const games = Game.find({ $or:[{ player_1: player._id }, { player_2: player._id }] });
res.json(games);
}
catch (err) {
res.json({ message: err });
}
});
I've been reading about .populate(), promises, and waterfalls, but I'm new to this and would love some guidance!
Please try this :
//GET ALL GAMES ASSOCIATED WITH PLAYER BY USERNAME
router.get('/username/:username', async (req, res) => {
try {
const player = await Player.findOne({ username: req.params.username });
console.log(player);
/**
* .findOne() should return a document or null - if no match found..
*/
if (player) {
/**
* .find() will return empty [] only if it didn't find any matching docs but won't throw an error in successful DB operation
* (irrespective of whether docs matched or not, if op is successful then there will be no error).
*/
const games = await Game.find({ $or: [{ player_1: player._id }, { player_2: player._id }] }).lean();
(games.length) ? res.json(games) : res.json(`No games found for ${player._id}`);
} else {
res.json('No player found')
}
}
catch (err) {
res.json({ message: err });
}
});
I fail to receive information from my postgres db when trying to connect with graphql.
I receive the following response:
{
"errors": [
{
"message": "password authentication failed for user \"admin\"",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"account"
]
}
],
"data": {
"account": null
}
}
I honestly don't know where to define the user and pass.
const express = require('express');
const expressGraphQL = require('express-graphql');
const schema = require('./schema');
const app = express();
app.use('/graphql', expressGraphQL({
schema,
graphiql: true
}))
app.listen(4000, () => {
console.log('Listening...')
})
and this is my schema file
const graphql = require('graphql');
const connectionString = 'myURI';
const pgp = require('pg-promise')();
const db = {}
db.conn = pgp(connectionString);
const {
GraphQLObjectType,
GraphQLID,
GraphQLString,
GraphQLBoolean,
GraphQLList,
GraphQLSchema
} = graphql;
const AccountType = new GraphQLObjectType({
name: 'account',
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
busines_name: { type: GraphQLString },
email: {
type: new GraphQLList(EmailType),
resolve(parentValue, args) {
const query = `SELECT * FROM "emails" WHERE
account=${parentValue.id}`;
return db.conn.many(query)
.then(data => {
return data;
})
.catch(err => {
return 'The error is', err;
});
}
}
})
})
const EmailType = new GraphQLObjectType({
name: 'Email',
fields: {
id: { type: GraphQLID },
email: { type: GraphQLString },
primary: { type: GraphQLBoolean }
}
})
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
account: {
type: AccountType,
args: { id: { type: GraphQLID } },
resolve(parentValue, args) {
const query = `SELECT * FROM "account" WHERE id=${args.id}`;
return db.conn.one(query)
.then(data => {
return data;
})
.catch(err => {
return 'The error is', err;
});
}
},
emails: {
type: EmailType,
args: { id: { type: GraphQLID } },
resolve(parentValue, args) {
const query = `SELECT * FROM "emails" WHERE id=${args.id}`;
return db.conn.one(query)
.then(data => {
return data;
})
.catch(err => {
return 'The error is', err;
});
}
}
}
})
module.exports = new GraphQLSchema({
query: RootQuery
})
I would like to know where to define the user and the password for the db of what i'm doing wrong besides that.
const connectionString = 'myURI';
It should be enough if your connection string includes the username and password. Is your DB connection string of the form postgres://username:password#server:5432 ?
See https://www.postgresql.org/docs/10/libpq-connect.html#LIBPQ-CONNSTRING
I am trying to make a list of permissions for a role,
here's what I am trying to do in my permissions,
const PermissionsSchema = new mongoose.Schema({
name: {
type: String,
index: true,
required: true,
},
createdAt: {
type: Date,
default: Date.now
}
});
PermissionsSchema.statics = {
get(id) {
return this.findById(id)
.exec()
.then((permission) => {
if (permission) {
return permission;
}
const err = new APIError('No such permission exists!', httpStatus.NOT_FOUND);
return Promise.reject(err);
});
},
list({ skip = 0, limit = 50 } = {}) {
return this.find()
.sort({ createdAt: -1 })
.skip(+skip)
.limit(+limit)
.exec();
}
};
module.exports = mongoose.model('Permission', PermissionsSchema);
and this in my roles model.
const RoleSchema = new mongoose.Schema({
name: String,
type: String,
permissions: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Permission'
}],
createdAt: {
type: Date,
default: Date.now
}
});
RoleSchema.statics = {
get(id) {
// const _id = mongoose.Types.ObjectId.fromString(id);
return this.findById(id)
// .populate('permissions')
.exec()
.then((role) => {
if (role) {
return role;
}
const err = new APIError('No such role exists!', httpStatus.NOT_FOUND);
return Promise.reject(err);
});
},
list({ skip = 0, limit = 50 } = {}) {
return this.find()
.populate('permissions')
.sort({ createdAt: -1 })
.skip(+skip)
.limit(+limit)
.exec();
}
};
module.exports = mongoose.model('Role', RoleSchema);
and when I try to get all, I get this error
Cast to ObjectId failed for value "ADD_USER" at path "_id" for model "Permission"
I've gone through some other posts but they all say I need to pass _id as a string, but I am not querying myself, how would I cast _id?
So I already had some documents in my collection which didn't have any kind of ID in them.