I am developing a sample API for restaurants in which I want retrieve data of restaurants by entering the Restaurant's name. Controller, Model & Router has been set but if I load it into Postman data doesn't appear. Please share some ideas.
Controller: (restaurant.js)
const restaurants = require('../Models/restaurantData');
exports.getRestaurantName = (req, res) => {
const Name = req.params.name;
restaurants.find({
name: Name
}).then(result => {
res.status(200).json({
message: "Restaurant Data",
restaurants: result[0]
});
}).catch(error => {
res.status(500).json({
message: error
});
});
}
Model: (restaurantData.js)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const restaurantSchema = new Schema({
_id: {
type: Number,
required: true
},
name: {
type: String,
required: true
},
city_name:{
type: String,
required: true
},
city_id: {
type: String,
required: true
},
location_id: {
type: Number,
required: true
},
area: {
type: Number,
required: true
},
locality:{
type: String,
required: true
},
thumb: {
type: String,
required: true
},
cost:{
type: Number,
required: true
},
address:{
type: String,
required: true
},
mealtype:{
type: Number,
required: true
},
name:{
type: String,
required: true
},
cuisine:{
type: Number,
required: true
},
type:{
type: Array,
required: true
},
Cuisine:{
type: Array,
required: true
}
});
module.exports = mongoose.model('restaurantData', restaurantSchema, 'restaurantData');
Router:
const express = require('express');
const restaurantController = require('../Controllers/restaurant');
const router = express.Router();
router.get('/restaurantData/:name',restaurantController.getRestaurantName);
module.exports = router;
had you add network access if yes then use Model.create(req.body(err,data)={ res.send(data); })
Change the following and I hope it will work.
In Restaurant Model, remove this:
module.exports = mongoose.model( "restaurantData", restaurantSchema, "restaurantData");
And add this:
const Restaurant = mongoose.model("restaurantData", restaurantSchema);
module.exports = { Restaurant };
In your Restaurant controller, change the import script into:
const { Restaurant } = require("../Models/restaurantData");
And Method will be:
Restaurant.find({
name: Name,
})
Change the variable and file names according to your need.
I think the problem might be while creating the model out of the schema
module.exports = mongoose.model('restrauntData', restaurantSchema);
use the above instead of
module.exports = mongoose.model( "restaurantData", restaurantSchema, "restaurantData");
then it should work fine.
Related
I was trying from some object get others info from it. Like from object A, get the objectId from object B, and printing the object B instead the object A. But I got this error message:
TypeError: Cannot read properties of null (reading 'idTechnical')
I'm using nodejs
My function:
const getFinalReport = async (req, res) => {
try{
const finalReport = await Final.findById(req.params.id);
const technicalReport = await Technical.findById(finalReport.idTechnical);
const finantialReport = await Finantial.findById(finalReport.idFinantial);
const writeReport = await Write.findById(finalReport.idWrite);
res.status(200).json(finalReport, {technicalReport, finantialReport, writeReport});
}catch(err){
console.error(err);
res.status(500).send({"msg": "Internal Error!"})
}}
My model:
const finalreportSchema = new mongoose.Schema({
idWrite: { type: mongoose.Schema.Types.ObjectId, ref: "reports", default:''},
idTechnical: { type: mongoose.Schema.Types.ObjectId, ref: "technincal", default: ''},
idFinantial: { type: mongoose.Schema.Types.ObjectId, ref: "finantial", default:''},
isConclude: { type: Boolean, default: false }
},
{
timestamps:true
});
const Report = mongoose.model('final-report', finalreportSchema);
module.exports = Report;
My techincal model:
const mongoose = require("mongoose");
const TechincalSchema = mongoose.Schema({
idInstallationNumber: { type: mongoose.Schema.Types.ObjectId, ref: "installations" },
months: { type: String, required: true },
previousBalance: { type: String, required: true },
actualBalance: { type: String, required: true },
injected: { type: String, required: true },
totalInjected: { type: String, required: true },
},
{
timestamps:true
});
const Technical = mongoose.model('technincal', TechincalSchema);
module.exports = Technical;
Same happen on the Finantial and Write Reports. Had someone had some clue?
Sorry for my english but, this is the first time asking, and also it's been a while that I write something in english (isn't my first language)
EDIT added mongoose.model.
I'm pretty new to mongodb and mongoose. I'm not able to populate books to authors in mongoose.
Can anyone help me with that? Here is my code. I removed unnecessary fields
const authorSchema = mongoose.Schema({
_id:{
type: String,
required: true,
unique: true,
trim: true
},
name: {
type: String,
required: true,
trim: true
},
books: [{
type: String,
ref: "Book"
}]
}, {_id:false})
const Author = mongoose.model('Author', authorSchema)
module.exports = {Author}
And my books schema looks as following
const bookSchema = mongoose.Schema({
_id:{
type:String,
required:true,
unique:true,
trim: true
},
name: {
type: String,
required: true,
trim: true,
unique: true
},
description:{
type: String,
trim: true,
default: 'No description specified'
},
datePublished: {
type: Date,
trim: true,
default: '01/01/2001'
},
author:{
type: String,
ref: 'Author',
required: true
}
}, {_id:false})
const Book = mongoose.model('Book', bookSchema)
module.exports = {Book}
Here is the route to populate them together
AuthorRouter.get('/authors/:id', async(req, res)=>{
const authorID = req.params.id
try {
const author = await Author.findById(authorID)
try {
const populated = await author.populate({path: 'books.book', select: 'name description -_id'})
console.log(populated);
res.status(201).send(populated)
} catch (e) {
res.status(401).send(`${e}\n Unable to populate categories`)
}
} catch (error) {
res.status(401).send('Unable to find author')
}
})
Output is following with empty books array:
{
"_id": "123",
"name": "testuser",
"books": [],
"__v": 0
}
Populating an arrays of refs works the same way as a single ref. Just call the populate method on the query and an array of documents will be returned in place of the original _id's.
In your case that would be:
const populated = await author.populate({path: 'books', select: 'name description -_id'});
Hey i have modify your code , try to use this one
This is your author schema file
const Schema = mongoose.Schema;
const authorSchema = mongoose.Schema({
_id:{
type: String,
required: true,
unique: true,
trim: true
},
name: {
type: String,
required: true,
trim: true
},
books: [{
type: Schema.Types.ObjectId,
ref: "bookSchema"
}]
}, {_id:false})
const Author = mongoose.model('Author', authorSchema)
module.exports = {Author}
And this is your route
AuthorRouter.get('/authors/:id', async(req, res)=>{
const authorID = req.params.id
try {
const author = await Author.findById(authorID)
try {
const populated = await author.find().populate('books');
console.log(populated);
res.status(201).send(populated)
} catch (e) {
res.status(401).send(`${e}\n Unable to populate categories`)
}
} catch (error) {
res.status(401).send('Unable to find author')
}
})
i have a schema of user that contain an array of movie
i create a new schema of Movie
but i get error of invalid schema configuration.
what i'm doning worng?
enter code here
const mongoose = require("mongoose");
const Movie = require("./movie-model");
const Schema = mongoose.Schema;
const User = new Schema({
firstName: { type: String, required: true },
lastName: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
movies: { type: Movie },
});
module.exports = mongoose.model("user", User);
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var Movie = new Schema(
{
name: { type: String, required: true },
time: { type: String, required: true },
rating: { type: Number, required: false },
priorety: { type: Number, required: true },
},
);
module.exports = mongoose.model("movie", Movie);
in movie-model
module.export = Movie
instead of
module.exports = mongoose.model("movie", Movie);
User has many movies
const mongoose = require("mongoose");
const Movie = require("./movie-model");
const Schema = mongoose.Schema;
const User = new Schema({
firstName: { type: String, required: true },
lastName: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
movies: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "movie",
},
],
});
module.exports = mongoose.model("user", User);
I invite you to read more about One-to-Many Relationships with Embedded Documents
You need to done referencing in User collection
movies: [
type: mongoose.Schema.ObjectId,
ref: 'user'
]
//instead of doing that
movies: { type: Movie },
Im relatively new to MongoDB and Mongoose. Im much used to MySQL so in used to inner joining tables on calls. Ive read a lot that you can link two Mongoose Schemas to achieve the same outcome. How would like like the two schemas together to when I make a call to get a chore by id it'll return the chore and then for the assignedTo & createdBy have the user scheme data for the said userId?
Chore Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ChoreSchema = new Schema({
title: {
type: String,
required: true
},
desc: {
type: String,
required: true
},
time: {
type: Number,
required: true
},
reaccurance: {
type: [{
type: String,
enum: ['Daily', 'Weekly', 'Bi-Weekly', 'Monthly']
}]
},
reward: {
type: Number,
required: true
},
retryDeduction: {
type: Number,
required: false
},
createdDate: {
type: Date,
default: Date.now
},
createdBy: {
type: String,
required: true
},
dueDate: {
type: Date,
required: true
},
status: {
type: [{
type: String,
enum: ['new', 'pending', 'rejected', 'completed', 'pastDue']
}],
default: ['new']
},
retryCount: {
type: Number,
default: 0,
required: false
},
rejectedReason: {
type: String,
required: false
},
familyId: {
type: String,
required: true
},
assignedTo: {
type: String,
required: false,
default: ""
}
});
let Chores = module.exports = mongoose.model('Chores', ChoreSchema);
module.exports.get = function (callback, limit) {
Chores.find(callback).limit(limit);
};
User Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
role: {
type: [{
type: String,
enum: ['Adult', 'Child']
}]
},
birthday: {
type: String,
required: false
},
familyId: {
type: String,
required: true
},
balance: {
type: Number,
required: true,
default: 0.00
}
});
let Users = module.exports = mongoose.model('Users', UserSchema);
module.exports.get = function (callback, limit) {
Users.find(callback).limit(limit);
};
Im trying to link ChoreSchema.createdBy & ChoreScheme.assignedTo by UserSchema._id
How I make the call in Node.js:
exports.index = function(req, res) {
Chore.get(function(err, chore) {
if (err)
res.send(err);
res.json({
message: 'Chore List',
data: chore
});
});
};
Mongoose has a more powerful alternative called populate(),
which lets you reference documents in other collections.
https://mongoosejs.com/docs/populate.html
Here is how you can link ChoreSchema.createdBy and ChoreScheme.assignedTo by UserSchema._id
var mongoose = require('mongoose');
const { Schema, Types } = mongoose;
var UserSchema = new Schema({
firstName: { type: String, required: true },
...
})
var ChoreSchema = new Schema({
title: { type: String, required: true },
...
//The ref option is what tells Mongoose which model to use during population
assignedTo: { type: Types.ObjectId, ref: 'Users' },
createdBy: { type: Types.ObjectId, ref: 'Users' },
})
let Chores = mongoose.model('Chores', ChoreSchema);
let Users = mongoose.model('Users', UserSchema);
Then in your express route handler you can populate assignedTo & createdBy like this
router.get('/chores/:id', function (req, res) {
const choreId = req.params.id;
Chores.find({ _id: choreId })
.populate('createdBy') // populate createdBy
.populate('assignedTo') // populate assignedTo
.exec(function (err, chore) {
if(err) {
return res.send(err)
}
res.json({ message: 'Chore List', data: chore });
});
})
const contactSchema = mongoose.Schema({
name: {
type:String,
required: true
},
mo_no: {
type: Number,
required: true
},
creator: {
type: mongoose.Schema.Types.ObjectId,
required: true
}
});
const Contact = module.exports = mongoose.model('Contact', contactSchema);
When I am executing this server sent 200 status but data are getting added. Any solution?