I am using nodejs,mongodb and mongoose. This query is not fetching match data from user and order table. I have read mongoose docs and alot of other articeles. It's according to it but doesn't fetch match data from tables.
Query code:
const data = await order
.find({ admin_id: req.params.id })
.populate("orderRelate");
console.log(data);
My user and order schema code is:
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema(
{
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
mobile_no: { type: Number, required: true },
profilePic: { type: String, defaut: "" },
owner: { type: Boolean, defaut: false },
},
{ timestamps: true }
);
const orderSchema = new mongoose.Schema(
{
customer_id: { type: String, required: true },
admin_id: { type: String, required: true },
order_type: { type: String, defaut: "normal" },
order_status: { type: String, required: true },
order_price: { type: Number, required: true },
order_address: { type: String, required: true },
order_pickDate: { type: String, required: true },
order_pickTime: { type: String, required: true },
orderRelate: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
},
{ timestamps: true }
);
module.exports = mongoose.model("User", UserSchema);
module.exports = mongoose.model("Order", orderSchema);
Please let me know if anyone know why I am facing this issue.
Thanks
Please try with findById maybe it's work
i don't know how you wrote your middleware function but..
await Order.find({orderRelate: req.user.id})
Related
I have a "cart" model, and within my "order" model, I would like to have an array that receives the information sent by "cart" stored in an array. How can I do this through ref?
const mongoose = require('mongoose');
const CartSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
},
note: {
type: String,
required: true,
},
price: {
type: Number,
required: false,
},
createdAt: {
type: Date,
default: Date.now,
}
},
{ timestamps: true }
);
module.exports = mongoose.model("Cart", CartSchema);
order
const mongoose = require('mongoose');
const OrderSchema = new mongoose.Schema(
{
list: {
name: String,
notes: String,
},
totalAmount: {
type: Number,
required: true,
},
payment: {
type: String,
required: true,
},
address: {
type: String,
required: true,
},
addressNote: {
type: String,
required: false,
},
createdAt: {
type: Date,
default: Date.now,
}
},
{ timestamps: true }
);
module.exports = mongoose.model("Order", OrderSchema);
Here in "list" I would like it to be an array that receives cart model information
Can I do this through ref? What would be the best possible way?
I am new to the backend and trying to learn by building some stuff but unfortunately, I got stuck.
I want to know if I can update a nested array of objects in Users Schema using Mongoose in an efficient and elegant way.
Users Schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: {
type: String,
required: true
},
username: {
type: String,
required: true,
unique: true
},
email: {
type: String,
required: true,
unique: true
},
gender: {
type: String,
required: true
},
password: {
type: String,
required: true
},
friends: [{}],
notifications: []
}, {timestamps: true});
module.exports = User = mongoose.model('user', UserSchema);
In the friends' field, I stored friend request with the status of pending
I want if the user whose the request was sent to, hits an endpoint, to accept the request
by changing the status from pending to success.
This is how a friend request was stored:
friendRequest = {
_id: req.user.id,
status: 'pending',
sentByMe: false,
new: true,
inbox: []
}
Thanks as you help me out!!! 🙏🙏🙏
You should first create an additional friendRequest and inbox schemas like this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
const InboxSchema = new Schema({
user_id: {
type: String,
required: true
},
from_id: {
type: String,
required: true
},
message: {
type: String,
required: true
},
the_date_time: {
type: Date,
required: true
}
});
mongoose.model('Inbox', InboxSchema);
const FriendRequestSchema = new Schema({
user_id: {
type: String,
required: true
},
status: {
type: String,
required: true
},
sentByMe: {
type: Boolean,
required: true,
unique: true
},
inbox: [InboxSchema]
})
mongoose.model('FriendRequests', FriendRequestSchema);
and update your Users schema:
const UserSchema = new Schema({
name: {
type: String,
required: true
},
username: {
type: String,
required: true,
unique: true
},
email: {
type: String,
required: true,
unique: true
},
gender: {
type: String,
required: true
},
password: {
type: String,
required: true
},
friends: [FriendSchema],
notifications: [FriendRequestSchema]
}, {timestamps: true});
And then use the friendRequest object
friendRequest = {
_id: req.user.id,
status: 'pending',
sentByMe: false,
new: true,
inbox: []
}
to update the Users collection
Users.update({ _id: user_id }, { $push: { notifications: friendRequest } });
Whenever you have arrays of objects within collections, its best to define additional schemas. You should also consider adding indexes to your collection schemas.
Update:
A FriendSchema would look like this:
const FriendsSchema = new Schema({
friend_id: {
type: String,
required: true
},
friend_name: {
type: String,
required: true
},
friendship_made: {
type: Date,
required: true
}
// you have to define FriendSchema before you define Users since you
// now reference [FriendSchema] in UserSchema
mongoose.model('Friends', FriendSchema);
And so is personA friends with personB?
Users.findOne({ "_id": personA.id, "friends.friend_id": personB.id});
I just started learning express and mongodb. I recently faced the kind of problem, I'm trying to select all the subdocuments which are inside of Room model.
const books = await Room.find().populate('book');
But it returns whole room document when i want to select only bookings field.
Here's the book schema
const bookSchema = new mongoose.Schema({
startDate: {
type: Date,
required: true,
},
endDate: {
type: Date,
required: true,
},
name: {
type: String,
required: true,
},
phone: {
type: String,
required: true,
},
});
module.exports = mongoose.model("book", bookSchema)
And here's the room schema
const roomSchema = new mongoose.Schema({
currentlyReserved: {
type: Boolean,
default: false,
},
people: {
type: Number,
required: true,
},
roomNumber: {
type: Number,
required: true,
},
pricePerPerson: {
type: Number,
required: true,
},
reservedUntil: {
type: Date,
default: null,
},
reservedBy: {
type: String,
default: null,
},
bookings: {
type: [{ type: mongoose.Schema.Types.ObjectId, ref: "book" }],
},
});
module.exports = mongoose.model("room", roomSchema);
You can project with with second arg to find().
https://docs.mongodb.com/manual/reference/method/db.collection.find/#projection
const books = await Room.find({}, {bookings: 1}).populate('bookings');
Having an issue with a model. Trying to do a model.findOne(), but I keep getting the error
Error:
TypeError: User.findOne(...).than is not a function
I definitely installed mongoose, but it seems I am no longer importing mongoose or the User model appropriately? Not sure.
User.js (model)
const mongoose = require('mongoose')
const Schema = mongoose.Schema
module.exports = User => {
var UserSchema = new Schema({
name: String,
email: { type: String, unique: true },
password: String,
passwordResetToken: String,
passwordResetExpires: Date,
document: String,
profile_picture: String,
ocupation: { type: Schema.Types.ObjectId, ref: 'Ocupation' },
is_admin: { type: Boolean, default: false },
sector: { type: Schema.Types.ObjectId, ref: 'Sector' },
is_manager: { type: Boolean, default: false },
group: { type: Schema.Types.ObjectId, ref: 'Group' },
is_team_leader: { type: Boolean, default: false },
can_start: { type: Boolean, default: true },
isVerified: { type: Boolean, default: false },
created_at: { type: Date, default: Date.now },
updated_at: { type: Date, default: Date.now },
deleted_at: Date,
}, {
toJSON: {
virtuals: true
}
})
UserSchema.virtual('profile_url').get(function() {
return `http://${process.env.HOST}:${process.env.NODE_ENV ? process.env.DEV_PORT : process.env.PORT}/3e002f70cbf8805c904bf1536a22a52e/${this.profile_picture}`
})
return mongoose.model('Users', UserSchema)
}
UserController.js
const User = require('../models/User')
myfunction(req, res) {
const { name, email } = req.body
let checkEmail = await User.findOne({ email })
}
whats wrong?
You're not exporting the model, but a factory(?) function for generating a model. Just remove:
module.exports = User => {
and instead, edit your return statement to:
module.exports = mongoose.model('Users', UserSchema');
Also, side note, it's usually a good idea to define your model in a singular form: User, not Users.
You'll have to create reference to your model & then export that to be used as reference to the Schema
Like this,
const mongoose = require('mongoose')
const Schema = mongoose.Schema
var UserSchema = new Schema({
name: String,
email: { type: String, unique: true },
password: String,
passwordResetToken: String,
passwordResetExpires: Date,
document: String,
profile_picture: String,
ocupation: { type: Schema.Types.ObjectId, ref: 'Ocupation' },
is_admin: { type: Boolean, default: false },
sector: { type: Schema.Types.ObjectId, ref: 'Sector' },
is_manager: { type: Boolean, default: false },
group: { type: Schema.Types.ObjectId, ref: 'Group' },
is_team_leader: { type: Boolean, default: false },
can_start: { type: Boolean, default: true },
isVerified: { type: Boolean, default: false },
created_at: { type: Date, default: Date.now },
updated_at: { type: Date, default: Date.now },
deleted_at: Date,
}, {
toJSON: {
virtuals: true
}
})
UserSchema.virtual('profile_url').get(function() {
return `http://${process.env.HOST}:${process.env.NODE_ENV ? process.env.DEV_PORT : process.env.PORT}/3e002f70cbf8805c904bf1536a22a52e/${this.profile_picture}`
})
var User = mongoose.model('Users', UserSchema)
module.exports = User;
I'm using Feathers.js with Mongoose and I want to create a field that cannot be changed by the services.
// account-model.js - A mongoose model
//
// See http://mongoosejs.com/docs/models.html
// for more of what you can do here.
const mongoose = require('mongoose');
require('mongoose-type-email');
module.exports = function(app) {
const mongooseClient = app.get('mongooseClient');
const recovery = new mongooseClient.Schema({
token: { type: String, required: true }
}, {
timestamps: true
});
const account = new mongooseClient.Schema({
firstName: { type: String, required: true },
surname: { type: String, require: true },
phone: { type: String, require: true },
email: { type: mongoose.SchemaTypes.Email, required: true, unique: true },
birth: { type: Date, required: true },
gender: { type: String, required: true },
country: { type: String, required: true },
address: { type: String, required: true },
address2: { type: String, required: false },
city: { type: String, required: true },
postcode: { type: String, required: true },
password: { type: String, required: true },
status: { type: String, required true }
}, {
timestamps: true
});
return mongooseClient.model('account', account);
};
No one can make a post at /account/<id> and change the field status.
This field should only be changed when internally. When some approval service request.
How can I implement this behavior?
This is a perfect use case for Feathers hooks. When accessed externally, in a service method call params.provider will be set so you can check for it and remove the field from data if it is:
module.exports = function() {
return async context => {
if(context.params.provider) {
delete context.data.status;
}
}
}
This hook will be a before hook for the create, update and patch method.