I'm calling findById using mongoose and it's not returning all fields, or at least it's not mapping to a field correctly. But it returns that field if I use aggregate
I have the following schema
const ratingSchema = new mongoose.Schema({
rating: {
type: Number,
default: 0,
min: 0,
max: 5
}
})
const locationSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
address: {
type: String,
required: true,
},
rating: ratingSchema,
facilities: [String],
});
locationSchema.index({coords: '2dsphere'});
mongoose.model('Location', locationSchema);
When I call
const Loc = mongoose.model('Location');
const locationsReadOne = (req, res) => {
Loc
.findById(req.params.locationid)
.exec((err, location) => {
if (!location) {
return res.status(404).json({"message":"location not found"});
} else if (err) {
return res.status(404).json(err);
}
console.log("locationsReadOne:",location);
res.status(200).json(location);
});
};
It returns the schema, but the rating field is not being returned. Here is a console.log of the returned object:
locationsReadOne: {
facilities: [ 'Hot drinks', 'Food', 'Premium wifi' ],
_id: 5f88bfdc4df4ca7709462865,
name: 'Starcups',
address: '125 High Street, Reading, RG6 1PS'
}
If I call Loc.aggregate, the rating field is returned:
{
_id: 5f8b2ee15b0b6784a847b600,
facilities: [ 'Tea', ' Restroom' ],
name: 'Tea Leaf',
address: '2192 Green St.',
rating: 0,
}
{
_id: 5f88bfdc4df4ca7709462865,
name: 'Starcups',
address: '125 High Street, Reading, RG6 1PS',
rating: 3,
facilities: [ 'Hot drinks', 'Food', 'Premium wifi' ]
}
Any idea why this would happen? I can clearly see the rating field in each of the documents in MongoDB compass and they are all listed as type Double. Why are they being returned in aggregate, but not in findById(id) or even in find()?
Thank you.
When you use find in mongoose, it will populate the document with the fields from the schema. For example - if you remove a field from the schema, you may not see that on the found document, even if it is in the database. Aggregate and Compass are showing you exactly what's in the database, so that data is there, it is just not being populated on the document because it doesn't see it on the schema.
The reason for that is your ratingSchema is an object with a rating property. So mongoose is looking for something like:
{
name: ...
rating: {
rating: 2
}
}
And not finding it, so it's not populating. To fix this, I would not define rating as a subschema, and instead define your schema as
const locationSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
address: {
type: String,
required: true,
},
rating: {
type: Number,
default: 0,
min: 0,
max: 5
},
facilities: [String],
});
Related
I am building a room booking system in nodejs. Currently I have hotels , rooms and bookings as collections.
rooms is referenced to hotels and bookings is referenced to rooms.
booking.js
const bookingSchema = new mongoose.Schema({
room: {
type: mongoose.Schema.Types.ObjectId,
ref: 'rooms'
},
start: Date,
end: Date
});
rooms.js
const roomSchema = new mongoose.Schema({
roomid: String,
hotel: {
type: mongoose.Schema.Types.ObjectId,
ref: 'hotel_managers'
},
type: String,
price: Number,
capacity: Number,
facilities: [String],
amenities: [String],
img: [String]
});
hotels.js
const hotel_manager_schema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
hotelname: {
type: String,
required: true
},
role: {
type: String,
default: 'manager'
},
location: {
type: String,
required: true
},
img:{
type: String,
required: true
}
})
N.B. This is a service provider ended system, so a hotel is basically a hotel manager with his credentials.
What i want to achieve is when a user sends a query for a given date range, I want to return all the available hotels as well as rooms in a hotel that don't have any booking in the query date range.
I am new in MongoDB so any tips or suggestions on how I can do what I want would be of great help.
Here's what you can do according to your schema model architecture; we wanna list all available hotels as well as rooms in hotels that don't have any booking at a given date range.
So to achieve this, we're gonna fetch all bookings that overlaps with date range provided in query and return their room ids; after that we fetch all rooms excluded the array of room ids returned from bookings.
const bookings = await Booking
.find({
$or: [
{ start: { $gte: from_date, $lte: to_date } },
{
end: { $gte: from_date, $lte: to_date }
},
{
$and: [{ start: { $lte: from_date } }, { end: { $gte: to_date } }]
},
],
})
.select('room');
const roomIds = bookings.map(b => b.room);
const availableRooms = await Room.find({ _id: { $nin: roomIds } })
You can extract hotel's data by populating Rooms hotel property field:
const availableRooms = await Room
.find({ _id: { $nin: roomIds } })
.populate('hotel', 'username password hotelname role location img')
I hope this would work for you.
i am expecting your database is already accumulated with some data and considering that all you have to do is just make a query in your bookingSchema.
const availableRoom = await Booking.find({ //query today up to tonight
created_on: {
$gte: new Date(2012, 7, 14),
$lt: new Date(2012, 7, 15)
}
})
Here Booking is a model. You can find details how to create model over HERE
You can find HERE how to query using dates
I know this question has been asked before, but after hours of research I have tried several ways to solve my problem without success.
Schema
const ValuationsSchema = new Schema(
{
value: { type: Number, required: true, min: 0, max: 5 },
author: {
type: Schema.Types.ObjectId,
refPath: "fromModel",
required: true,
},
fromModel: {
type: String,
required: true,
enum: ["usertype1", "usertype2", "usertype3"],
trim: true,
},
},
{
timestamps: true,
}
);
const UserSchema = new Schema(
{
name: { type: String, required: true, trim: true },
valuations: [ValuationsSchema],
},
{
timestamps: true,
}
);
What am I trying to do
I am trying to populate the author field of ValuationsSchema, in the valuations array of a user.
Sample data
Result expected
{
_id: 5f1ef9f6039fea10c437939c,
name: 'Jose Maria',
createdAt: 2020-07-27T15:59:50.529Z,
updatedAt: 2020-08-01T15:34:47.414Z,
valuations: [
{
_id: 5f258b973c0ac544869c0434,
value: 5,
author: Object,
fromModel: 'particular',
createdAt: 2020-08-01T15:34:47.414Z,
updatedAt: 2020-08-01T15:34:47.414Z
}
]
}
Result gotten
{
_id: 5f1ef9f6039fea10c437939c,
name: 'Jose Maria',
createdAt: 2020-07-27T15:59:50.529Z,
updatedAt: 2020-08-01T15:34:47.414Z,
valuations: [
{
_id: 5f258b973c0ac544869c0434,
value: 5,
author: 5f1edaa83ce7cf44a2bd8a9a,
fromModel: 'particular',
createdAt: 2020-08-01T15:34:47.414Z,
updatedAt: 2020-08-01T15:34:47.414Z
}
]
}
Already tried solutions
At the moment I manually populated the field, but as it is a good practice, I am trying to use the API when possible.
As far as I am concerned executing this should get the job done, but it doesn't.
await user.populate("valuations.author").execPopulate();
Also tried this without luck:
await user.populate({
path: "valuations",
populate: {
path: "author",
},
}).execPopulate();
Tried the deepPopulate package too, but yet same result.
The refPath should be from parent level valuations.fromModel,
Change it in your schema,
author: {
type: Schema.Types.ObjectId,
refPath: "valuations.fromModel",
required: true,
}
Single document wise population,
let user = await User.find();
let user1 = await user[0].populate("valuations.author").execPopulate();
All documents population
let users = await User.find().populate("valuations.author").execPopulate();
Note: There is a bug #6913 in mongoose version 5.2.9, refPath not working in nested arrays, Make sure you have installed latest version.
I have a schema:
var userSchema = new Schema({
name: String,
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
admin: Boolean,
created_at: Date,
updated_at: Date
});
Let's assume I have made 100 Users using this schema.
Now I want to change the schema:
var userSchema = new Schema({
name: String,
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
admin: Boolean,
created_at: Date,
friends: [Schema.Types.ObjectId], //the new addition
updated_at: Date
});
I need all new Users to have this field. I also want all of the 100 existing Users to now have this field. How can I do this?
You can use Mongoose Model.update to update all your documents in the collection.
User.update({}, { friends: [] }, { multi: true }, function (err, raw) {
if (err) return handleError(err);
console.log('The raw response from Mongo was ', raw);
});
I don't recommend to do it in production if the collection is big, since it is a heavy operation. But in your case it should be fine.
Using the query interface in a client app or your terminal you could do:
db.users.updateMany({
$set: { "friends" : [] }
});
Here's the docs reference.
it doesn't work for me :x
Here is my code
let test = await this.client.db.users.updateMany({
$set: { "roles" : [] }
});
and the output
{ ok: 0, n: 0, nModified: 0 }
I don't know how to do, i tried a lot of things and uh it doesn't work :'(
EDIT: I found, here is my code
await this.client.db.users.updateMany({ }, [ {$set : { "roles": []} } ]);
I have a model with nested object and I want to update single field of that document but unable to do it. I could not understand why it's not working.
This is my model
var sampleItemSchema = new Schema({
id: {
type: String,
required: true
},
content: {
type: Object,
required: true
},
location: Object,
createdAt: {
type: Date,
default: Date.now
},
sample: {type: mongoose.Schema.Types.ObjectId, ref: 'Sample'}
});
And this is my one of document.
{ createdAt: Thu Apr 21 2016 19:46:17 GMT+0200 (CEST),
__v: 0,
sample: 571911df9a97810c3f35d83d,
location: { city: 'Kildare' },
content:
{ images: [],
price: { currency: 'EUR', amount: 2000 },
createdAt: '2016-04-21T17:46:17.349Z',
category: { id: '2012', name: 'Animals | Ponies' },
body: 'Beaulieu Ginger Pop (Ben) is a 14 year old 13.2hh grey roan New Forest pony. He has a full green passport, is microchipped and is fully up...',
title: '13.2hh All rounder Gelding' },
id: '12123191',
_id: 571911e99a97810c3f35d845 }
Here what I tried yet.
I am just giving part of code
models.SampleItem.find({
sample: sample
}, function(err, sampeItemList) {
console.log('Total sample: ', sampeItemList.length);
async.eachSeries(sampeItemList, function(item, next) {
item.content.body = "want to update this field";
item.save(function(err, updatedItem) {
console.log('Updated description...', index);
})
})
})
Am I doing something wrong?
Mongoose does not allow you to use Object as a schema type. Instead set the type to Schema.Types.Mixed. This will give you an object with whatever properties you want to set.
You can see the list of all the valid schema types in the Mongoose Schema Types documentation.
(You probably want to change the location field to Schema.Types.Mixed as well.)
Mongoose doesn't allow 'Object' as a type. Use 'Schema.Types.Mixed' for properties which have flexible/unknown values.
var SecuritySchema = new Mongoose.Schema({
_bids: [{
type: Mongoose.Schema.Types.ObjectId,
ref: 'BuyOrder'
}],
_asks: [{
type: Mongoose.Schema.Types.ObjectId,
ref: 'SellOrder'
}]
});
var OrdersSchema = new Mongoose.Schema({
_security: {
type: Mongoose.Schema.Types.ObjectId,
ref: 'Security'
},
price: {
type: Number,
required: true
},
quantity: {
type: Number,
required: true
}
});
// declare seat covers here too
var models = {
Security: Mongoose.model('Security', SecuritySchema),
BuyOrder: Mongoose.model('BuyOrder', OrdersSchema),
SellOrder: Mongoose.model('SellOrder', OrdersSchema)
};
return models;
And than when I save a new BuyOrder for example:
// I put the 'id' of the security: order.__security = security._id on the client-side
var order = new models.BuyOrder(req.body.order);
order.save(function(err) {
if (err) return console.log(err);
});
And attempt to re-retrieve the associated security:
models.Security.findById(req.params.id).populate({
path: '_bids'
}).exec(function(err, security) {
// the '_bids' array is empty.
});
I think this is some sort of naming issue, but I'm not sure, I've seen examples here and on the moongoose website that use Number as the Id type: http://mongoosejs.com/docs/populate.html
The ref field should use the singular model name
Also, just do:
models.Security.findById(req.params.id).populate('_bids').exec(...
My main suspicion given your snippet at the moment is your req.body.order has _security as a string instead of an array containing a string.
Also, you don't need an id property. Mongodb itself will automatically do the _id as a real BSON ObjectId, and mongoose will add id as a string representation of the same value, so don't worry about that.
While I don't understand your schema (and the circular nature of it?), this code works:
var order = new models.BuyOrder({ price: 100, quantity: 5});
order.save(function(err, orderDoc) {
var security = new models.Security();
security._bids.push(orderDoc);
security.save(function(err, doc) {
models.Security.findById({ _id: doc._id })
.populate("_bids").exec(function(err, security) {
console.log(security);
});
});
});
It:
creates a BuyOrder
saves it
creates a Security
adds to the array of _bids the new orderDoc's _id
saves it
searches for the match and populates
Note that there's not an automatic method for adding the document to the array of _bids, so I've done that manually.
Results:
{ _id: 5224e73af7c90a2017000002,
__v: 0,
_asks: [],
_bids: [ { price: 100,
quantity: 5,
_id: 5224e72ef7c90a2017000001, __v: 0 } ] }