Let's say I have these two models below and i want to get or fetch the location of a specific user using mongoose in node:
User Model
const userSchema = new mongoose.Schema({
name: {
type: String,
minlength: 2,
maxlength: 50,
},
email: {
type: String,
minlength: 5,
maxlength: 255,
unique: true,
},
password: {
type: String,
minlength: 5,
maxlength: 1024,
},
});
And Location Model
const locationtSchema = new mongoose.Schema({
name: {
type: String,
minlength: 5,
maxlength: 50,
},
lat: {
type: String,
required: true,
},
lng: {
type: String,
required: true,
},
user: {
type: userSchema,
required: true,
},
});
So, I tried to resolve it like this... but it didn't work.
const location = Location.find({
'user._id': req.params._id
})
How can i return locaitons of a specific user?
The id you are trying to pass is a string, instead, it should be an object id
const location = Location.find({
'user._id': mongoose.Types.ObjectId(req.params._id)
})
It would work perfectly now.
Related
I am trying to create a new document in the Form collection. This document references many FormSection documents. Here are the Schemas:
const FormSchema = new Schema({
title: {
type: String,
required: true,
unique: true
},
description: {
type: String,
required: true,
unique: true
},
sections: [{
type: FormSectionDetails
}],
createdDate: {
type: String,
required: false,
unique: true
},
lastEdited: {
type: String,
required: false,
unique: true
}
});
const FormSectionDetails = new Schema({
section: {
type: Schema.Types.ObjectId,
ref: 'FormSection',
required: true
},
position: {
type: Number,
required: true
}
});
const FormSectionSchema = new Schema({
name: {
type: String,
required: true,
unique: true
},
display: {
type: String,
required: true,
},
category: {
type: String,
required: true
},
...
});
let FormSection;
try {
FormSection = mongoose.connection.model('FormSection');
} catch (e) {
FormSection = mongoose.model('FormSection', FormSectionSchema);
}
However, when I try to add a new document to the Forms collection, I get an error:
Document being inserted:
formData = {
"title": "Returning Members",
"description": "Returning Members",
"sections":
[{
"section": "6292c0fbd4837faca1d85d4d",
"position": 1
},
{
"section": "6292c0fbd4837faca1d85d4e",
"position": 2
},
...
}
Code being run:
formdata.sections.map(s => {
return {
...s,
section: ObjectId(s.section),
}}
);
return await FormSection.create(formdata);
Error message:
ValidationError: category: Path `category` is required., display: Path `display` is required.````
Seems like it is trying to create a new FormSection document. I don't want it to create a new FormSection document. I just want it to reference existing FormSection documents using the Object IDs I specified.
The Issue seems to be with how you declare the section field in the FormSchema. Try this:
const FormSchema = new Schema({
title: {
type: String,
required: true,
unique: true
},
description: {
type: String,
required: true,
unique: true
},
sections: [{
type: ObjectId,
ref: 'FormSectionDetails',
required: true,
}],
createdDate: {
type: String,
required: false,
unique: true
},
lastEdited: {
type: String,
required: false,
unique: true
}
});
This would just store the _ids of the existing FormSectionDetails
It turns out I was inserting the document into the wrong collection. Instead of the code snippet:
return await FormSection.create(formdata);
It should actually be:
return await Form.create(formdata);
The error message should have been a more obvious hint for me as to what the problem was.
I want to store empty array in user schema's friends key. But, mongoose won't let me to add empty array of friends.
Here's my User schema
const userSchema = mongoose.Schema({
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
userName: {
type: String,
unique: true,
required: true,
},
email: {
type: String,
required: true,
unique: true,
validate: [validator.isEmail, "Please enter a valid Email"],
},
password: {
type: String,
required: true,
minlength: [6, "Password must be at least 6 characters"],
},
friends: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
unique: true,
},
],
});
And here's my code to pull data from array and save empty array
const index = req.user.friends.findIndex(friend => friend.toString() === req.params.id);
if(index !== -1){
req.user.friends.splice(index, 1);
}else{
req.user.friends.push(req.params.id);
}
const user = new User(req.user);
await user.save({validateBeforeSave: false});
return res.json({success: true});
specify default value instead
friends: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
unique: true,
default: []
},
],
I have a user which should have the following fields and currently has following schema:
const UserSchema = new Schema(
{
email: {
type: String,
required: true,
index: { unique: true },
lowercase: true,
},
isVerified: { type: Boolean, default: false }, // whether user has confirmed his email
name: { type: String, required: false },
password: { type: String, required: true, minLength: 6 }, // object with next two included?
passwordResetExpires: Date,
passwordResetToken: String,
roles: [{ type: 'String' }], // Array of strings?
username: { type: String, required: false },
token: [{ type: String, required: false }], // used to send verification token via email
},
{ timestamps: true },
);
So yes, what is the world's default standard for organising user schemas. This schema's fields are pretty common, right?
This is my Table Collection:
const tableSchema = new Schema({
number: {
type: Number,
required: true,
unique: true
},
seats: {
type: Number,
required: true
},
reservations: [orderSchema]
})
const Table = mongoose.model('Table', tableSchema)
And OrderSchema:
const orderSchema = new Schema({
time: {
type: String,
required: true
},
date: {
type: String
},
user: userSchema
})
And User Collection and Schema:
const userSchema = new Schema({
firstname: {
type: String,
required: true
},
lastname: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
phone: {
type: String
},
password: {
type: String,
required: true
},
admin: {
type: Boolean,
default: false,
required: true
}
})
const User = mongoose.model('User', userSchema)
When i would like to create the second (i have no idea why first is adding) instance of table, i am getting error like in title:
MongoError: E11000 duplicate key error collection: restauracja.tables index: reservations.user.email_1 dup key: { : null }
I can create only one document in table, but i have different values in the second one.
Here is my code. I have a review schema in a separate file called "review.js".
const express = require('express');
const mongoose = require('mongoose');
const User = require('../model/user');
require('mongoose-currency').loadType(mongoose);
const Currency = mongoose.Types.Currency;
const Schema = mongoose.Schema;
let reviewSchema = new Schema();
reviewSchema.add({
rating: {
type: Number,
min: 1,
max: 5,
defualt: 0
},
howEasyToMake: {
type: Number,
required: true,
min: 1,
max: 5
},
howGoodTaste: {
type: Number,
required: true,
min: 1,
max: 5,
},
wouldMakeAgain: {
type: Number,
required: true,
min: 1,
max: 5,
},
comment: {
type: String,
default: ""
},
postedBy: {
type: String,
required: true,
index: true
},
reviewOf: {
type: String,
required: true,
index: true
},
postersCreationDate: {
type: Number,
required: true
},
chefsCreationDate: {
type: Number,
required: true
},
chefsId: {
type: String,
required: true
}
});
module.exports.reviewSchema = reviewSchema;
I have another file called recipe.js, where I import reviewSchema and use it as an embedded schema for my Recipe model schema.
const express = require('express');
const mongoose = require('mongoose');
const User = require('../model/user');
require('mongoose-currency').loadType(mongoose);
const Currency = mongoose.Types.Currency;
const Schema = mongoose.Schema;
const reviewSchema = require('../model/review').reviewSchema;
let recipeSchema = new Schema({
name: {
type: String,
required: true
},
description: {
type: String,
},
steps: {
type: String,
required: true,
},
ingredients: {
type: Array,
default: ['1', '2', '3', '4']
},
category: {
type: String,
required: true,
index: true
},
postedBy: {
type: String,
required: true,
},
reviewsOfRecipe: [reviewSchema],
numberOfRatings: {
type: Number,
default: 0
},
totalAddedRatings: {
type: Number,
default: 0
},
reviewAverage: {
type: Number,
default: undefined
},
postersCreationDate: {
type: Number,
index: true
},
likedBy: {
type: Array
},
reviewedBy: {
type: Array
}
});
recipeSchema.methods.updateReviewAverage = function(){
let recipe = this;
this.reviewAverage = this.totalAddedRatings / this.numberOfRatings;
};
let Recipe = mongoose.model('Recipe', recipeSchema);
module.exports = Recipe;
I have another file called recipeRouter.js where I use reviewSchema to construct a review to then later insert it into the embedded reviewsOfRecipes array in my Recipe document. In my recipRouter.js file, every time my code tries to do this....
Recipe.findOne({name: req.params.name}).then((recipe) => {
let review_ = new reviewSchema({
comment: req.body.comment
rating: req.body.score
});
recipe.reviewsOfRecipe.push(review_);
})
...I get this error.
TypeError: reviewSchema is not a constructor
Previously, when I ran into this problem, I had the reviewSchema in the same file as my Recipe model schema. Since then, I split the two into each having their own file. And I made sure to properly export module.exports.reviewSchema = reviewSchema; in my review.js file, and made sure to have const reviewSchema = require('../model/review').reviewSchema; in both my recipe.js and recipeRouter.js files. Yet still this issue still comes up/ I would greatly appreciate it if someone could point out what may be the issue.
You have to export reviewSchema like you did to the other schema (using mongoose.model):
module.exports.reviewSchema = mongoose.model('Review', reviewSchema);