Append to array nodejs mongodb - arrays

I am trying to append a string to an array that will be used to identify a user in multiple chatrooms. I have tried and can not get this to work. The log does not put out anything but:
[]
if (req.body.method == "setid") {
if(req.locals.user.chatid == null){
req.locals.user.chatid = {};
}
app.model.User.update(
{ _id: req.locals.user._id },
{ $addToSet: { chatid: [{mid: req.body.value}]} }
);
} else if (req.body.method == "checkid" && req.body.value) {
app.model.User.find({
"chatid": req.body.value
}, function(err, FoundUser) {
if (err || !FoundUser) {
res.end("ERROR");
} else {
console.log(FoundUser);
res.end(FoundUser[0].displayName);
}
});
}
Mongo Structure
{
email: { type: String, index: { unique: true }, required: true },
password: { type: String },
changeName: {type: Boolean},
displayName: { type: String, index: { unique: true }, required: true },
avatar: { type: String, default: '/assets/anon.png' },
permissions: {
chat: { type: Boolean, default: true },
admin: { type: Boolean, default: false }
},
online: { type: Boolean, default: true },
channel: { type: Types.ObjectId, ref: 'Channel', default: null }, //users channel
banned: { type: Boolean, default: false },
banend: {type:String, default: ''},
subs: [{ type: Types.ObjectId, ref: 'User' }],
about: { type: String },
temporary: {type: Boolean, default: false},
chatid:[{mid: {type:String}}]
}

Let's focus only on below snippet of code:
app.model.User.update(
{ _id: req.locals.user._id },
{ $addToSet: { chatid: [{mid: req.body.value}]} }
);
First, please verify whether you are getting a user in this query or not. Maybe, you are not getting the user at the first place and hence update won't work. Moreover, you will not get any error in this scenario.
Secondly, if you are getting the user then update your $addToSet query as: { $addToSet: { chatid: {mid: req.body.value}}}. These square brackets might cause an issue here.
Your query seems fine to me, which makes me doubt the parameters you are passing. Make sure that req.body.value is not null or undefined. In that case, the update won't happen and you will not get any error also!

Related

Sequelize unkown column in field list error

I have a MySql DB and using sequelize.
I have a recipe and ingredients tables.
I want to pass the ingredients as an array to the api.
So I researched and discovered I can use get/set to achieve this.
But I get an "Unknown coumn 'ingredients' in 'field list'".
This is my model. The line
console.info("getDataValue...", this);
never gets executed.
function model(sequelize) {
const attributes = {
recipeTitle: { type: DataTypes.STRING(255), allowNull: false },
category: { type: DataTypes.STRING(30), allowNull: false },
recipeSource: { type: DataTypes.STRING(100), allowNull: false },
recipeSourceData: { type: DataTypes.TEXT(), allowNull: true },
method: { type: DataTypes.TEXT(), allowNull: true },
comments: { type: DataTypes.TEXT(), allowNull: true },
prepTime: { type: DataTypes.STRING(10), allowNull: true },
cookTime: { type: DataTypes.STRING(10), allowNull: true },
rating: { type: DataTypes.FLOAT, allowNull: false },
owner_id: { type: DataTypes.INTEGER, allowNull: false },
ingredients: {
type: DataTypes.TEXT,
get() {
console.info("getDataValue...", this);
return JSON.parse(this.getDataValue("ingredients"));
},
set(val) {
if (!Array.isArray(val)) {
throw new Error("ingredients must to be an array");
}
this.setDataValue("ingredients", JSON.stringify(val));
},
},
};
This is my validate-request middle ware and it does have the ingredients
when i console.info("valreq...").
So it seems its the schema.validate that fails??
function validateRequest(req, next, schema) {
console.info("valreq...", req.body);
const options = {
abortEarly: false, // include all errors
allowUnknown: true, // ignore unknown props
stripUnknown: true, // remove unknown props
};
const { error, value } = schema.validate(req.body, options);
if (error) {
next(`Validation error: ${error.details.map((x) => x.message).join(", ")}`);
} else {
console.info("value...", value);
req.body = value;
next();
}
}

I am having difficulty accessing this nested array to carry out an update

SCHEMA
Below is my schema structure, kindly correct me if I am getting it wrong. I want to be able to update the ConnectState from false to true using an ObjectId
phones: {
type: String,
required: true,
},
User: {
type: mongoose.Schema.Types.ObjectId,
ref: "user",
// required: true,
},
Userpost: {
type: mongoose.Schema.Types.ObjectId,
ref: "userpost",
// required: true,
},
friendshipStatus: [
{
isFriend: {
FProfile: {
type: mongoose.Schema.Types.ObjectId,
ref: "profile",
},
ConnectStatus: {
type: Boolean,
default: false,
},
},
},
],
});
What I have tried
I want to update the Boolean value on ConnectStatus from false to true. I know I am getting the process wrong.
const result = await Profile.updateOne(
{ "friendshipStatus.isFriend.FProfile": uid },
{ $set: { "friendshipStatus.$.isFriend.ConnectStatus": true } },
{ arrayFilters: [{ "friendshipStatus.isFriend.FProfile": uid }] }
);
Try with:
const result = await Profile.update(
{ 'friendshipStatus.isFriend.FProfile': uid },
{ $set: { 'friendshipStatus.$.isFriend.ConnectStatus': true } },
);

Mongoose updating subdocument array

I want to update rooms subdocument which is in Property document, but I get this error:
MongoServerError: Updating the path 'rooms.$.updatedAt' would create a
conflict at 'rooms.$'
Error which i got in postman:
{
"ok": 0,
"code": 40,
"codeName": "ConflictingUpdateOperators",
"$clusterTime": {
"clusterTime": {
"$timestamp": "7137698220989218823"
},
"signature": {
"hash": "34spx6E0zZFa5bVYFSL2JyjFszQ=",
"keyId": {
"low": 2,
"high": 1646669662,
"unsigned": false
}
}
},
"operationTime": {
"$timestamp": "7137698220989218823"
}
}
My property model:
import { IReview, ReviewSchema } from './reviews.model'
import { IRoom, RoomSchema } from './room.model'
type TCheapestRoom = {
roomType: string
bedType: string
lastPrice: number
actualPrice: number
}
export interface IProperty {
propertyType: string
name: string
description: string
city: string
photos: [string]
cheapestRoom: TCheapestRoom
adress: string
distance: number
cancellationPolicy: string
meals: string
funThingsToDo: [string]
accessibility: [string]
rooms: IRoom[]
reviews: IReview[]
}
interface IPropertyDocument extends IProperty, Document {
createdAt: Date
updatedAt: Date
// rooms: Types.Array<IRoom>
}
const PropertySchema = new Schema<IPropertyDocument>(
{
propertyType: { type: String, required: true },
name: { type: String, required: true },
description: { type: String, required: true },
city: { type: String, required: true },
photos: { type: [String] },
cheapestRoom: {
roomType: { type: String },
bedType: { type: String },
lastPrice: { type: Number },
actualPrice: { type: Number },
},
adress: { type: String, required: true },
distance: { type: Number, required: true },
cancellationPolicy: { type: String, required: true },
meals: { type: String, required: true },
funThingsToDo: { type: [String] },
accessibility: { type: [String] },
rooms: [RoomSchema],
reviews: [ReviewSchema],
},
{
timestamps: true,
}
)
const PropertyModel = model<IPropertyDocument>('Property', PropertySchema)
export default PropertyModel
Subdocument room model:
export interface IRoom {
roomType: string
bedTypes: [string]
roomFacilities: [string]
sleeps: number
lastPrice: number
actualPrice: number
cancellation: string
payment: string
breakfast: string
unavailableDates: [Date]
}
export interface IRoomDocument extends IRoom, Document {
createdAt: Date
updatedAt: Date
}
export const RoomSchema = new Schema<IRoomDocument>(
{
roomType: { type: String, required: true },
bedTypes: { type: [String], required: true },
roomFacilities: { type: [String], required: true },
sleeps: { type: Number, required: true, default: 2 },
lastPrice: { type: Number, required: true },
actualPrice: { type: Number, required: true },
cancellation: { type: String, required: true },
payment: { type: String, required: true },
breakfast: { type: String, required: true },
unavailableDates: { type: [Date] },
},
{
timestamps: true,
}
)
const RoomModel = model<IRoomDocument>('Room', RoomSchema)
export default RoomModel
room controller:
import PropertyModel from '../models/property.model'
import RoomModel from '../models/room.model'
const updateRoom = async (req: Request, res: Response) => {
try {
const updatedProperty = await PropertyModel.findOneAndUpdate(
{ _id: req.params.propertyId, 'rooms._id': req.params.roomId },
{
$set: { 'rooms.$': req.body },
},
{
new: true,
}
)
res.status(201).json(updatedProperty)
} catch (error) {
console.log(error)
res.status(400).json(error)
}
}
export { addNewRoom, deleteRoom, updateRoom }
I want to be able updating my subdocuments, in this case rooms using property id and room id.
How can i update this subdocument ?

Save current User into field within array in Mongoose

Here is a relevant part of my Schema, where I'll make reservations to a "space":
var spaceSchema = new mongoose.Schema({
spaceName: String,
scheduledDates: [{
scheduledDates: String,
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
username: String
}
}]
});
Author should be the current user that's logged in. Here is my route to update those fields:
router.put('/:space_id/schedule', function(req, res) {
Space.findByIdAndUpdate(req.params.space_id, {
'$push': { 'scheduledDates': req.body.space, 'author': req.user._id }
}, { "new": true, "upsert": true }, function(err, space) {
if (err) {
console.log(err);
} else {
console.log(req.body.space);
}
});
});
I can't access "author" correctly, because it's inside the array. What can I do to update this array, adding a new date and user to make the reservation?
Thank you
UPDATE
I tried to use "_id" instead of "id" in my property but got the same result. It seems like it's ignoring the "author" field, and only saving "scheduledDates"
So the schema was like this:
scheduledDates: [{
scheduledDates: String,
author: {
_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
username: String
}
}]
And then in my route, I changed what I was 'pushing':
'$push': { 'scheduledDates': req.body.space, 'author._id': req.user._id }
UPDATED 2
Changed the way I was getting the object to push:
'$push': {
'scheduledDates': {
'scheduledDates': req.body.space,
'author': { _id: req.user._id, username: req.user.username }
}
}
Now I'm getting the following error:
message: 'Cast to string failed for value "{ scheduledDates: \'04/11/2017\' }" at path "scheduledDates"',
name: 'CastError',
stringValue: '"{ scheduledDates: \'04/11/2017\' }"',
kind: 'string',
value: [Object],
path: 'scheduledDates',
reason: undefined } } }

Mongoose: 'Cast to embedded failed for value at path. Cannot use 'in' operator to search for '_id'

I'm having some trouble trying to save an array inside an array of objects.
I'm getting the following response from the server:
{ [CastError: Cast to embedded failed for value "\'maxbeds: 4\'" at path "saved_searches"]
message: 'Cast to embedded failed for value "\\\'maxbeds: 4\\\'" at path "saved_searches"',
name: 'CastError',
kind: 'embedded',
value: '\'maxbeds: 4\'',
path: 'saved_searches',
reason: [TypeError: Cannot use 'in' operator to search for '_id' in maxbeds: 4] }
Here's my Schema:
var mongoose = require('mongoose'),
rfr = require('rfr'),
passwordHelper = rfr('server/helpers/password.js'),
Schema = mongoose.Schema,
_ = require('lodash');
/*
*
* Creating UserSchema for MongoDB
*
*/
var UserSchema = new Schema({
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true,
select: false
},
name: {
type: String,
required: true
},
passwordSalt: {
type: String,
required: true,
select: false
},
saved_houses: [{
mlsId: {
type: String
},
addressFull: {
type: String
},
bedrooms: {
type: Number
},
listPrice: {
type: Number
},
bathrooms: {
type: Number
},
sqft: {
type: Number
},
createdAt: {
type: Date,
default: Date.now
}
}],
saved_searches: [{
search_name: {
type: String
},
filters: {
type: [Schema.Types.Mixed]
},
createdAt: {
type: Date,
default: Date.now
}
}],
active: {
type: Boolean,
default: true
},
createdAt: {
type: Date,
default: Date.now
}
});
// compile User model
module.exports = mongoose.model('User', UserSchema);
The problem, I believe is the filters array that live inside an object inside the saved_searches array
Now, in my router I do the following:
var express = require('express'),
savedDataRouter = express.Router(),
mongoose = require('mongoose'),
rfr = require('rfr'),
s = rfr('server/routes/config/jwt_config.js'),
User = rfr('server/models/User.js'),
jwt = require('jsonwebtoken');
savedDataRouter.post('/searches', function (req, res) {
if (mongoose.Types.ObjectId.isValid(req.body.userId)) {
User.findByIdAndUpdate({
_id: req.body.userId
}, {
$push: {
saved_searches: {
search_name: req.body.search_name,
$each: req.body.filters
}
},
}, {
new: true
},
function (err, doc) {
if (err || !doc) {
console.log(err);
res.json({
status: 400,
message: "Unable to save search." + err
});
} else {
return res.json(doc);
}
});
} else {
return res.status(404).json({
message: "Unable to find user"
});
}
});
If I log the request body coming from the client I get the following:
//console.log(req.body)
{ search_name: 'Sarasota',
filters: [ 'minbaths: 1', 'maxbaths: 3', 'minbeds: 2', 'maxbeds: 4' ],
userId: '583359409a1e0167d1a3a2b3' }
I've tried all the things I've seen in Stack Overflow and other online resources with no luck. What am I doing wrong?
Edit
Added module dependencies to my UserSchema and SavedDataRouter
try this
User.findByIdAndUpdate({
_id: req.body.userId
}, {
$push: {
saved_searches: {
search_name: req.body.search_name,
filters: req.body.filters
}
},
}, {
new: true
},
function (err, doc) {
if (err || !doc) {
console.log(err);
res.json({
status: 400,
message: "Unable to save search." + err
});
} else {
return res.json(doc);
}
});

Resources