Node.js - mongoose. Cannot make a query on an ObjectId - node.js

This is my first time asking a question here.
I am using node.js and mongoose and I have the following three schemas:
var CustomerCouponSchema = new Schema({
coupon: { type: Schema.ObjectId, ref: 'Coupon' }
});
var CouponSchema = new Schema({
isActive: { type: Boolean, default: false },
supermarket: { type: Schema.ObjectId, ref: 'Supermarket' }
});
var SupermarketSchema = new Schema({
name: { type: string }
});
When I am trying to perform the following query:
//I have a variable named supermarketId which is an ObjectId
CustomerCoupon.find({ isUsed: false })
.populate({
path: 'coupon',
match: {
supermarket: { $or: [{ $eq: null }, { $eq: supermarketId }] },
isActive: true,
}
}).exec(function(err, data) {
});
I get the following error: Can't use $or with ObjectId.
Any help would be welcome

Related

How to push items in to an array which was referenced in collections schema in mongoose, nodejs

i want to create an item and push it into items array which was referenced in my collections schema. What i am sending in the payload is item properties and collection id. But i am getting CastError. Please help
COLLECTION SCHEMA
const collectionSchema = new Schema(
{
name: { type: String },
description: { type: String },
owner: { type: Schema.Types.ObjectId, ref: "User" },
items: [{ type: Schema.Types.ObjectId, require: true, ref: "Item" }],
},
{ timestamps: true }
);
export default model("Collection", collectionSchema);
ITEM SCHEMA
import mongoose from "mongoose";
const { Schema, model } = mongoose;
const itemSchema = new Schema(
{
name: { type: String },
description: { type: String },
owner: { type: Schema.Types.ObjectId, ref: "User" },
likes: [{ type: Schema.Types.ObjectId, ref: "User" }],
collections: { type: Schema.Types.ObjectId, ref: "Collection" },
},
{ timestamps: true }
);
export default model("Item", itemSchema);
CREATE ITEM ROUTE
itemRouter.post("/", JWTAuthMiddleware, async (req, res, next) => {
const item = new ItemModal(req.body)
const collection = await CollectionModal.findByIdAndUpdate(
req.user._id,
{
$push : { items: [{ ...req.body, id: item._id }] },
},
{ new: true }
);
res.send(collection);
});
What i am getting is an CASTERROR

query multiple nested objects

I have a problem while querying mongodb with nested multiple objects.
I am trying like this
Project.find()
.then((project) => {
RoadMap.find({
scheduledDate: {
$gte: new Date(req.params.gte), $lt: new
Date(req.params.lt)
}
})
.populate("roadMap", "_id title")
.populate("projectId", "_id title photo ")
.exec((err, roadmap) => {
if (err) {
return res.status(422).json({ error: err });
}
res.json({ project, roadmap });
});
})
.catch((err) => {
return res.status(404).json({ error: "project not found" });
});
I am getting results like this
{
project: {
}
roadmap: [{}{}]
}
but I want to achieve like this
{
project: {
_id:
title:
roadmap: [{},{}]
}
}
this is my schema:
projectShema:
const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema.Types;
const projectSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
},
photo: {
type: String,
required: true,
},
caption: {
type: String,
},
postedBy: {
type: ObjectId,
ref: "User",
},
news: [
{
type: ObjectId,
ref: "News",
},
],
roadMap: [
{
type: ObjectId,
ref: "RoadMap",
},
],
},
{ timestamps: true }
);
mongoose.model("Project", projectSchema);
roadMapSchema:
const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema.Types;
const roadmapSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
},
postedBy: {
type: ObjectId,
ref: "User",
},
projectId: { type: ObjectId, ref: "Project" },
categoryName: { type: String },
status: {
type: String,
default: "created",
},
},
{ timestamps: true }
);
mongoose.model("RoadMap", roadmapSchema);
I am not sure how to achieve the results, do I need to change schema or it is possible here also?
thank you

Accessing object in array of arrays using mongoose

I have the following structure and am trying to remove an object in participants (league.division.participants).
var participantSchema = new mongoose.Schema({
player: { type: mongoose.Schema.Types.ObjectId, ref: 'Player' },
record: { type: mongoose.Schema.Types.ObjectId, ref: 'ParticipantRecord' },
events: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Event' } ]
});
var divisionSchema = new mongoose.Schema({
name: String,
participants: [ participantSchema ]
});
var leagueSchema = new mongoose.Schema({
name: String,
startDate: { type: Date, default: Date.now },
endDate: Date,
locked: Boolean,
leagueType: { type: mongoose.Schema.Types.ObjectId, ref: 'LeagueType' },
game: { type: mongoose.Schema.Types.ObjectId, ref: 'Game' },
divisions: [ divisionSchema ],
});
mongoose.model('League', leagueSchema);
var _RemoveDivisionParticipant = function(participantId)
{
return new Promise((resolve,reject) =>{
Models.League.findOne({'divisions.participants._id':participantId})
.populate('divisions')
.populate('divisions.participants')
.exec((err, league) => {
if (err) {return reject(err)}
league.divisions(XXXXX).participants(participantId).remove();
console.log(league.divisions[0].participants[0])
})
})
}
This is what i have so far, but obviously it returns the league object, and i have no way of getting to the participants since I don't know which division the participant is in (Shown by XXXXX in the sample). Any pointers as to what I should do?
You can use $pull to remove an array element based on a condition :
League.update({
'divisions.participants._id': participantId
}, {
$pull: {
'divisions.$.participants': {
"_id": participantId
}
}
}, { multi: true }, function(err, res) {
console.log(res);
});

MongoError in filter with $elementMatch

I'm using Mongoose in my NodeJS backend for a chat.
I want to filter all the messages from conversation that the user don't read it in my MongoDB db:
controller
var filter = {
$and:[
{
conversation:req.conversation.id
},
{
$not:
{
readers:
{
$elemMatch:
{
user:req.user.id
}
}
}
}
]
};
Message
.find(filter)
.exec(function(err,messages){
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
console.log(messages);
res.jsonp(true);
}
});
Debugging this code:
messages-> undefined
err-> Error {name: 'MongoError'}
And the filter variable:
I don't understand the error, I think maybe I applied wrong the filter... What is incorrect in my code?
Thank you so much!! I share the Message shema below:
message shema
var MessageSchema = new Schema({
conversation:{
type: Schema.ObjectId,
ref: 'Conversation'
},
created: {
type: Date,
default: Date.now
},
user:{
type: Schema.ObjectId,
ref: 'User'
},
message:{
type: String,
default:''
},
readers:[{
date: {
type: Date,
default: Date.now
},
user:{
type: Schema.ObjectId,
ref: 'User'
}
}]
});

mongoose unable to find refs using $in operator

I have a user schema like this
var userSchema = new mongoose.Schema({
username: String,
following: [{created: {type: Date, default: Date.now}, target: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }}]
});
And a user activity schema:
var activity = new mongoose.Schema({
text: String,
private: Boolean,
_creator: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }
});
I'm trying to get all the activites where the _creator is $in the following sub-document of the user.
userModel.methods.getNewsfeed = function(callback){
var following_targets = _.pluck(this.following, 'target') // using underscore.js
activityModel.find(
{
$or: [
{
_creator: this._id
}
,
{
$and: [
{ private: { $ne: true } }
, {'_creator': { $in: following_targets }}
]
}
]
}
)
.exec(callback);
}
However this query only returns activites created by the current user. Removing the _creator: this._id part returns an empty array.
I found what was wrong.
I manually inserted sample user documents using the mongo shell, the target in the following array was a String instead of ObjectId, so mongoose could not find it.

Resources