Mongoose populate replacing ObjectIds with empty array - javascript

I've been trying to use the mongoose populate function to connect two models. I can save an object but when trying to retrieve using populate the ObjectIds are just replaced with an empty array.
Many questions seem to have been asked but none have a solution that worked for me
user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Route = require('./route')
var passportLocalMongoose = require('passport-local-mongoose');
const postSchema = new Schema ({
text: {
type: String,
default: '',
required: true
}
}, {
timestamps: true
});
const UserSchema = new Schema({
firstname: {
type: String
},
posts: [postSchema],
route: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Route'
}]
}, {
timestamps: true
});
UserSchema.plugin(passportLocalMongoose);
const User = mongoose.model('User', UserSchema);
module.exports = User;
route.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
const locationSchema = new Schema ({
id: {
type: Number,
default: 0,
required: true
},
address: {
type: String,
default: '',
required: true
},
lat: {
type: Number,
default: 0,
required: true
},
lng: {
type: Number,
default: 0,
required: true
}
},{
timestamps: true })
const routeSchema = new Schema ({
locations: [locationSchema],
description: {
journey1: {
type: String,
default: '',
required: false
},
journey2: {
type: String,
default: '',
required: false
},
journey3: {
type: String,
default: '',
required: false
},
journey4: {
type: String,
default: '',
required: false
}
}
}, {
timestamps: true
});
module.exports = mongoose.model('Route', routeSchema);
within REST POST end point
User.findOne({_id: req.user._id}, function(err,user) {
if(user) {
var routed = new Route();
routed.locations = req.body.locations;
routed.description = req.body.description;
user.route.push(routed);
user.save()
.then((user) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json')
res.json(user)
}, (err) => next(err))
} else {
console.log("errored")
err = new Error('User ' + req.body.username + ' not found');
err.status = 404;
return next(err);
}
})
within REST GET end point
User.findOne({_id: req.user._id})
.populate('route')
.then((user) => {
if(user){
console.log("user")
console.log(user)
console.log("routes")
console.log(user.route)
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json')
res.json({success: true, routes: user.route});
}
}, (err) => next(err))
.catch((err) => next(err));
If I remove populate I'll get something like
[
new ObjectId("61f053af7ba46267f4893f8f")
new ObjectId("61f053af7ba46267f4893f8f")
new ObjectId("61f053af7ba46267f4893f8f")
]
from the GET end point but adding it back in returns
[].
My understanding is that in 'new Route()' I'm creating a new Route Object with an Id that gets stored in the User model/document(?). Then when I call populate mongoose searches the Route document for those Ids and converts them to the objects I want. The only issue I could think of is that I'm not creating the Route objects correctly and so no object is being stored with that Id which is why an empty array is returned when I come to try swap Ids with Route objects.
Any ideas or are we all just stumbling in the dark ?

Not entirely sure this is the correct method but instead of instantiating a Route object as displayed I used the Route.create(...) method and then pushed that to the route array and now populate works as expected

Related

I get this error: this.$__.validationError = new ValidationError(this)

I am new to learning web dev using node.js and express.js. When I test my code in Postman the server crashes and gives me this error this.$__.validationError = new ValidationError(this).
I am creating backend server connected to MongoDB and the mongoose package.
Routes
const express = require('express')
const router = express.Router()
const {
create
} = require('./../controllers/courseControllers')
const {verifyAdmin, verify} = require('./../auth')
router.post('/create', verifyAdmin, async (req, res) => {
// console.log(req.body)
try{
create(req.body).then(result => res.send(result))
}catch(err){
res.status(500).json(err)
}
})
Controllers
const Course = require('../models/Course');
//CREATE A COURSE
module.exports.create = async (reqBody) => {
const {courseName, description, price} = reqBody
let newCourse = new Course({
courseName: courseName,
description: description,
price: price
})
// console.log(newCourse)
return await newCourse.save().then((result, err) => result ? result : err)
}
Schema
const mongoose = require('mongoose');
const courseSchema = new mongoose.Schema({
courseName: {
type: String,
required: [true, `Course name is required`],
unique: true
},
description: {
type: String,
required: [true, `Course description is required`]
},
price: {
type: Number,
required: [true, `Price is required`]
},
isOffered: {
type: Boolean,
default: true
},
enrollees: [
{
userId: {
type: String,
required: [true, `userId is required`]
},
enrolledOn: {
type: Date,
default: new Date()
}
}
]
}, {timestamps: true})
module.exports = mongoose.model("Course", courseSchema);
Given the information you provided, i can say that you are missing the enrollees parameter on creation whitin the controller, as enrollees has been set to required, i hope its usefull for you, if not let me know.

Building A Referral System Using Nodejs

So am still kinda new to nodejs and am currently on a project and would to integrate a referral sytem into it. Basically on registering a user has a generated unique url that ither users can register with, i have gotten pass this part but now am trying to link the new user and the user who owns the link.
Here are my Models:
Referral Model
import mongoose, { mongo } from 'mongoose';
const referralSchema = new mongoose.Schema({
referralId: [
{
type: String,
unique: true
}
],
referralLink: {
type: String,
unique: true
},
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
},
createdAt: {
type: Date,
default: Date.now()
}
})
const Referral = mongoose.model("Referral", referralSchema);
export default Referral;
User Model
import mongoose from 'mongoose';
import passportLocalMongoose from 'passport-local-mongoose'
const userSchema = new mongoose.Schema({
firstName: String,
lastName: String,
email: {
type: String,
trim: true,
required: true,
unique: true,
lowercase: true
},
emailToken: String,
isVerified: Boolean,
username: String,
password: String,
isAdmin: Boolean,
refId: {
type: mongoose.Schema.Types.ObjectId,
ref: "referral",
},
walletId: {
type: mongoose.Schema.Types.ObjectId,
ref: "wallet",
},
plan: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "plan",
}
]
})
userSchema.plugin(passportLocalMongoose);
const User = mongoose.model("User", userSchema);
export default User;
And Here is my code
router.get('/verify-email', async (req, res, next) => {
try {
const user = await User.findOne({ emailToken: req.query.token });
if (!user) {
req.flash('error', 'Token is invalid, Please contact us for assistance');
return res.redirect('/');
}
user.emailToken = null;
user.isVerified = true;
const savedUser = await user.save().then((user) => {
//Create new referral for new user
const newReferrer = new Referral({
referralId: uuidv4(),
referralLink: uuidv4(),
userId: user._id,
});
//save referral to the database
newReferrer.save()
const customUserResponse = { user: savedUser }
customUserResponse.refCode = newReferrer.referralId
req.login(user, async (err) => {
if (err)
return next(err);
req.flash('success', `Welcome to Jenerouszy Mechanism ${user.username}`);
const redirectUrl = req.session.redirectTo || `/dashboard`;
delete req.session.redirectTo;
res.redirect(redirectUrl);
});
});
} catch (error) {
console.log(error);
req.flash('error', 'Something went wrong, please try again or contact us for assistance')
res.redirect('/')
}
});
router.get("/referrals", middlewareObj.isLoggedIn, (req, res) => {
Referral.findOne({ userId: req.user._id })
.populate('user') //Populate model with user
.then(loggedUser => {
//Generate random referral link
const generatedRefLink = `${req.protocol}://${req.headers.host}/register?reflink=${loggedUser.referralLink}/dashboard`
res.render('dashboard/referrals', {
loggedUser: loggedUser,
generatedRefLink: generatedRefLink
})
})
})
I don't know how to go about this, can someone please guide me on what to do.

Mongoose returning empty array

I have a db in Mongo with 2 collections, users and campaigns. For the former, all of my requests (get,post, patch, etc...) work correctly. However, I am having an issue with campaigns.
I can create a new campaign in postman but not 'get' the campaigns. THe request appears successful but returns an empty array.
I have the campaigns split into:
campaignController,
***Model,
***Routes,
and a handlerFactory to cover users and campaigns.
handlerFactory:
exports.getAll = Model =>
catchAsync(async (req, res, next) => {
// To allow for nested GET reviews on tour (hack)
let filter = {};
if (req.params.campaignId) filter = { campaign: req.params.campaignId };
const features = new APIFeatures(Model.find(filter), req.query)
.filter()
.sort()
.limitFields()
.paginate();
// const doc = await features.query.explain();
const doc = await features.query;
// SEND RESPONSE
console.log('-------', doc);
res.status(200).json({
status: 'success',
results: doc.length,
data: {
data: doc
}
});
});
Campaign Model:
const campaignSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Campaign name can not be empty!']
},
clientID: {
type: String,
},
creator_id: {
type: String,
},
budget: {
type: Number,
min: 100,
required: [true, 'Campaign name can not be empty!']
},
startStatus: {
type: String,
enum: ['preStart', 'isStarted', 'preEnd'],
default: 'preStart'
},
startDate: {
type: Date,
},
createdAt: {
type: Date,
default: Date.now
},
updatedAt: {type: Date,
default: Date.now
},
isDeleted: {
type: Boolean,
// required: [true, 'Must be true or false!']
default: false
},
Priority: {
type: Boolean,
default: false,
},
location: {
type: String,
enum: ['Helsinki', 'Tallinn'],
default: 'Helsinki'
}
});
campaignSchema.pre('save', function(next) {
if (!this.isModified('createdAt') || this.isNew) return next();
this.updatedAt = Date.now() - 1000;
next();
});
campaignSchema.pre(/^find/, function(next) {
// this points to the current query
this.find({ isDeleted: { $ne: false } });
next();
});
const Campaign = mongoose.model('Campaign', campaignSchema);
module.exports = Campaign;
campaignController:
exports.getAllCampaigns = factory.getAll(Campaign);
exports.getCampaign = factory.getOne(Campaign);
exports.createCampaign = factory.createOne(Campaign);
exports.updateCampaign = factory.updateOne(Campaign);
exports.deleteCampaign = factory.deleteOne(Campaign);
exports.getMe = (req, res, next) => {
req.params.id = req.campaign.id;
next();
};
exports.deleteCurrentCampaign = catchAsync(async (req, res, next) => {
await User.findByIdAndUpdate(req.campaign.id, { active: false });
res.status(204).json({
status: 'success',
data: null
});
});
campaignRoutes:
const router = express.Router();
router
.route('/')
.get(campaignController.getAllCampaigns)
.post(
authController.protect,
authController.restrictTo('admin', 'super-admin'),
campaignController.createCampaign
);
router
.route('/:id')
.get(campaignController.getCampaign)
.patch(
authController.protect,
authController.restrictTo('admin', 'super-admin'),
campaignController.updateCampaign
)
.delete(
authController.protect,
authController.restrictTo('admin', 'super-admin'),
campaignController.deleteCampaign
);
module.exports = router;
Any idea where I am going wrong?
All code looks good but may be problem is,your collection not contain any records whose isDeleted=true.
because "find query middleware" in campaignModel is called before any find* query and it find all document whose isDeleted != false.

Adding new attribute to existent document with mongoose

I'm trying to update an existing document to add a new attribute with js.
User.findOne({ name: req.body.user.name }).exec((err, user) => {
// Handle database errors
if (err) {
res.status(500).send(err);
} else {
user['name'] = req.body.user.name;
user['mail'] = req.body.user.mail;
user['apikey'] = req.body.user.apiKey;
console.log('ApiKey: ' + req.body.user.apiKey);
console.log('User: ' + user );
user.save((err, saved) => {
if (err) {
console.log("error");
res.status(500).send(err)
}
res.json({ user: saved });
});
}
});
But it seems that I can't add the new one base on the logs.
The new one It's not a required field. This is my model:
const userSchema = new Schema({
name: { type: 'String', required: true },
mail: { type: 'String', required: true },
password: { type: 'String', required: true },
apiKey: { type: 'String', required: false }
});
let User = mongoose.model('User', userSchema);
I'm just getting started with mongoDB using mongoose so I'm have many basic things wrong.

Mongoose "find" returns an empty array

i'm trying to find all blogs that a user has created with his userId.
I have the following mongoose model for the blog
var mongoose = require('mongoose');
var BlogSchema = new mongoose.Schema({
title:{
type: String,
required: true,
},
content:{
type: String,
required: true
},
_creator:{
type: mongoose.Schema.Types.ObjectId,
required: true
}
})
BlogSchema.statics.findBlogs = function(id){
var Blog = this;
return Blog.find(id).then((blog)=>{
console.log(blog)
}).catch((e)=>{
console.log('failed')
})
}
var Blog = mongoose.model('Blogs', BlogSchema)
module.exports = {Blog};
then in my server.js i have this
app.get('/get/blogs', authenticate, (req, res)=>{
var userId = req.user._id
console.log(userId)
Blog.findBlogs(userId).then((data)=>{
res.send(data)
}).catch((e)=>{
res.sendStatus(404)
})
})
but it returns an empty array, how should i approach this?
The line
return Blog.find(id).then((blog) => {
should probably say
return Blog.find({ _creator: id }).then((blogs) => {
Try this
blog.find({creatorid:user.id},function(err,data){
//data will be here
})

Categories

Resources