mongoose find not fetching any result - node.js

I've simple collection in mongo and a corresponding mongoose model. This collection will only contain one document always. When I run a query in mongoshell it is giving me the result, but when I try to do findOne using mongoose it is not returning any result at all. Can someone help me figure out what is wrong. Below is my code.
Model:
const mongoose = require('mongoose');
const schema = new mongoose.Schema({
lastResetMonth: {
type: Number
},
lastResetWeek: {
type: Number
},
currentFisYear:{
type: Number
}
});
module.exports = mongoose.model('ReserveResetTrack', schema, 'reserveResetTrack');
const ReserveResetTrack = require('../models/ReserveResetTrack');
ReserveResetTrack.findOne({})
.then(trackData => {
return {
lastFisMonth: trackData.lastMonth,
lastFisWeek: trackData.lastWeek
}
});
The above code is always returning nothing but a promise.
This is the only document i've in my collection and this will be the only one for ever
{
"_id" : ObjectId("589271a36bfa2da821b13ce8"),
"lastMonth" : 0,
"lastWeek" : 0,
"currentYear" : 0
}

Use exec() like this:
ReserveResetTrack.findOne({})
.exec() // <--- use exec() here
.then(trackData => {
return {
lastFisMonth: trackData.lastMonth,
lastFisWeek: trackData.lastWeek
}
});

Related

mongodb issue when using .find()

I am using MongoDB for the first time and I came across an error that I could not solve.
Here is my code:
const mongoose = require('../../common/services/mongoose.service').mongoose;
const Schema = mongoose.Schema;
const functions = require('./functions');
const userSchema = new Schema({
email: String,
password: String,
number: String,
state: Boolean
});
userSchema.virtual('id').get(function () {
return this._id.toHexString();
});
// Ensure virtual fields are serialised.
userSchema.set('toJSON', {
virtuals: true
});
userSchema.findById = function (cb) {
return this.model('Users').find({id: this.id}, cb);
};
const User = mongoose.model('Users', userSchema);
exports.findByEmail = (email) => {
//console.log('hello'); //this works btw
return User.find({email: email});
};
So in the code above, findByEmail works fine since hello is logged. However, when it gets to return User.find, I get this error: SyntaxError: Unexpected token g in JSON at position 0.
This is what is currently in the DB:
{
"_id" : ObjectId("6026b813f1828a51f8979616"),
"email" : "gogo#gmail.com",
"password" : "GLImDln1xMKfKS/E99s8qg==$Es3PIHD95vV89973Xq4RecveYMEf22PCH/pFtG1+xq4Gtc4DelA/JXlRNcOR11Rfv/J1uaZCuOplsEmHhY0ehQ==",
"number" : "6969",
"state" : true,
"__v" : 0
}
I input gogo#gmail.com. Does anyone know what I am doing wrong? It would mean a lot to me. I am using node/vue btw.
Error occurs within findByEmail when I run it

Node.js and Mongoose. Reading from one collection and writing to a different one

I am trying to read from one Mongo collection and then take all that data and save it to a new collection. I am using the same schema, but changing the collection name in two different models :
UserInfo.js :
const mongoose = require('mongoose')
const userSchema = mongoose.Schema({
userID : String,
userName : String
})
let userInfo = mongoose.model('UserInfo', userSchema)
let backUpUserInfo = mongoose.model('BackUpUserInfo', userSchema)
module.exports = {
userInfo : userInfo,
backUpUserInfo : backUpUserInfo
}
I inserted data into the userinfos collection and then I am trying to read that and insert into the backupuserinfos collection :
backup.js :
const UserInfo = require('../Schema/UserInfo').userInfo;
const BackUpUserInfo = require('../Schema/UserInfo').backUpUserInfo;
async function backUp(){
UserInfo.find({}, async function(err1, userInfo){
if (err1) return console.log(err1)
for(let i in userInfo){
try{
let backUpUser = new BackUpUserInfo(userInfo[i])
await backUpUser.save(function (err2, user) {
if (err2) return console.error(err2)
console.log("collection updated")
})
}
catch(err){
console.log(err)
}
}
})
}
I am getting an error that seems to indicate that it is finding a duplicate when trying to save the information, even though the backup collection is empty. This makes me think it is trying to write to the user info collection instead of the back up one. I created the backUp model variable and that is what I run save on, which makes me think it should be specified to run to that collection. Am I doing something wrong here?
Here is the error :
VersionError: No matching document found for id
Easiest way in mongoose would be
UserInfo.aggregate([ { $match: {} }, { $out: "BackupUserInfo" } ])
Else you can use mongodb query OR mongodb copyTo()
db.myoriginal.aggregate([ { $match: {} }, { $out: "mycopy" } ])
//OR
db.source.copyTo("target");
But copyTo() is deprecated since version 3.0.

NodeJS Mongoose updateOne giving no match every time

I am trying to update a document in mongo with mongoose using updateOne method:
const updateResult = await UserModel.updateOne({
_id: mongoose.Types.ObjectId(userId)
}, {
$set: {
a: 'B'
}
})
userId contains a string of the ID of the user.
I have tried using the following
1. { _id: userId }
2. { email: theEmailOfTheUser }
But still, the updateResult is
n:0, nModified:0, ok:0
So I think it's must be something with the method itself and not in my query.
Also, when I'm trying to find the user using the query below, it can find it:
const user = await UserModel.find({
_id: userId
});
//user is found
Actually mongoose takes care of the $set and you do not have to add it. just:
const updateResult = await UserModel.updateOne({
_id: userId
}, {
a: 'B'
})
but the better solution would to just use findByIdAndUpdate():
const updateResult = await UserModel.findByIdAndUpdate(userId, {
a: 'B'
})

Mongoose - Can't push a subdocument into an array in parent Document

I am trying to push a subdocument(ApplicationSchema) into my Job schema. But it doesn't seem to work.
Following is my Job Schema :
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
var ApplicationSchema = require('./Application');
const Job = new Schema({
skills : {
type : Array
},
active : {
type : Boolean,
default : false
},
applications: [ApplicationSchema],
userId : {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
},{timestamps : true});
export default mongoose.model("Job", Job)
This is subdocument(ApplicationSchema). I have 5 more subdocuments in this schema.
I am pushing an object with a key-value pair of talentId and its value. But it doesn't work.
I get a new object in the array but the object I'm trying to push is not pushed.
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
var notesSchema = require('./notesSchema');
var documentSchema = require('./documentSchema');
var assessmentSchema = require('./assessmentSchema');
var interviewScheduleSchema = require('./interviewScheduleSchema');
var referenceSchema = require('./referenceSchema')
const ApplicationSchema = new Schema({
talentId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Talent'
},
applicationType: {
type: Number
}
notes: [notesSchema],
documents: [documentSchema],
assessment: [assessmentSchema],
interviewSchedule: [interviewScheduleSchema],
references: [referenceSchema]
},{
timestamps: true
});
export default ApplicationSchema;
Following is my code in the API endpoint
.post((req, res, next) => {
Job.findById(req.params.jobId)
.then((job) => {
if (job != null) {
job.applications.push(req.body);
job.save()
.then((job) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(job);
})
}
else {
err = new Error('Job ' + req.params.jobId + 'not found')
err.status = 404;
return next(err);
}
}, (err) => next(err))
.catch((err) => next(err));
})
req.body contains following object
{ talentId: '5a813e1eb936ab308c4cae51' }
If you already have the id of the job document then you can push application object direct by doing the following:
Job.update(
{ _id: req.params.jobId },
{ $push: { applications: req.body} },
callback
);
or you can use promise to handle this. and if you are only saving id of the application then you may want to change your job schema to store Id of the applications instead of whole application schema.
Please read the documentation carefully as this is very basic update query.
You have,
talentId: {type: mongoose.Schema.Types.ObjectId,
ref: 'Talent'}
But your req.body contains:
{ talentId: '5a813e1eb936ab308c4cae51' }
It should be:
{ talentId: mongoose.Types.ObjectId('5a813e1eb936ab308c4cae51') }
Turns out there was nothing wrong with code.
I was using import and export default syntax which didn't seem work well with this.
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
and
export default ApplicationSchema;
I replaced them with Common JS syntax and everything worked fine.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
and
module.exports = ApplicationSchema;
I did this for Job document file and every subdocument file and the code worked.

How to use $in in mongoose reference schema

I have 2 schemas 1st is city and second is pincode. Pincode having reference of city. They both look like this
CITY schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a all city list
var allCitySchema = new Schema({
cities: {
type: String
}
}, {collection: 'allcities'});
var allcities = mongoose.model('allcities', allCitySchema);
module.exports = allcities;
Pincode schemas
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var allPincode = new Schema({
city_id: {
type: Schema.ObjectId,
ref: 'allcities'
},
pincode: {
type: String
}
}, {collection: 'pincode'});
var allPincode = mongoose.model('pincode', allPincode);
module.exports = allPincode;
Now the problem is when i tried to fetch all pincode based upon city id for that i tries like this
app.post('/api/getPincodeByCity', function(req, res) {
console.log("In pincode");
var cities_id = [];
cities_id = req.body.cities_id;
console.log(req.body); // { cities_id: '["5597aa08c0a0beb40be128d4","5597aa2bbb18fefc142b6915"]' }
console.log(cities_id);
pincodes.findById( {city_id: { $in: cities_id }}, function(err,pincodeIds){
if(err) res.send(err.message);
res.send(pincodeIds);
res.end('{"success" : "Recieved Successfully", "status" : 200}');
});
});
But it's not working its giving me this error
Cast to ObjectId failed for value "[object Object]" at path "_id"
I also try with find() instead of findById() method but it giving me this error
undefined is not a function
The $in operator is not just "strictly" for querying arrays as that can be done with basically any operator for a singular value.
It's actually a "list of arguments" which evaluates to an $or condition, but with shorter syntax:
var idList = ["559e0dbd045ac712fa1f19fa","559e0dbe045ac712fa1f19fb"];
var pincode = mongoose.model('pincode');
pincode.find({ "city_id": { "$in": idList } },function(err,docs) {
// do something here
});
Which as mentioned is short form for this:
pincode.find(
{
"$or": [
{ "city_id": "559e0dbd045ac712fa1f19fa" },
{ "city_id": "559e0dbe045ac712fa1f19fb" }
]
},
function(err,docs) {
// do something here
}
)
You are getting an error because you are overwriting the "array" definition with a "string" which is what all "request" objects are unless parsed otherwise.
The other reason for the error is you are calling the wrong method. .findById() expects a single argument of the _id for the document. To query other fields use .findOne() or in this case .find() since an $in will possibly match more than one document.

Resources