Change field in object in array of object - mongodb

I have a field achivment with an array of objects. I need to update the field currentPoints in one object that I will find by field name in the array.
Code model of mongoose:
const achive = new Schema(
{
achiveId: ObjectId,
name: { type: String, required: true },
finishedPoints: { type: Number, required: true },
currentPoints: {
type: Number,
default: 0,
set: function (v) {
if (v >= this.finishedPoints) this.isFinished = true;
return v;
}
},
isFinished: { type: Boolean, default: false }
},
{ _id: false }
);
const achivesSchema = new Schema({
userId: ObjectId,
achivement: [achive]
});
Code query:
export async function progressAchive(req, res) {
const value = 3;
try {
const test = await Achives.updateOne(
{
userId: req.user._id,
achivement: { $elemMatch: { name: req.params.nameAchive } }
},
{ $set: { achivement: { currentPoints: value } } },
{ new: true }
);
res.json(test);
} catch (e) {
console.log(e);
}
}
Instead of updating, it removes all objects from the array and leaves them one object with the currentPoint field. How can I update this like I want?

You should use the following for update
const test = await Achives.updateOne(
{
userId: req.user._id,
},
{
$set:{"achivement.$[el].currentPoints": value}
},
{
arrayFilters:[{
"el.name": req.params.nameAchive
}],
new: true
}
);

Related

How to update any amount of fields in a nested documen in Mongoose?

I need to update different fields of a nested array in Mongoose. Sometimes I will send runId and runStatus, some other times siteFetched and some other times siteInfo.
I have tried with the following code but the $set operator replaces the old fields.
The model:
campaignId: { type: String },
keywords: [{
keyword: { type: String },
serp: {
runId: { type: String },
runStatus: { type: String },
siteFetched: { type: Boolean },
sitesInfo: [{
title: { type: String },
url: { type: String },
description: { type: String },
}],
},
},
],
Here is the code to update
const campaign = await Campaign.findOneAndUpdate(
{ _id: campaignId, "keywords.keyword": keyword },
{
$set: { "keywords.$.apifySerp": {...serp }},
}
);
the value for serp varies like
const serp = {
runId: '1kLgbnvpADsDJyP1x',
runStatus: 'READY'
}
and
const serp = {
siteFetched: true
}
Here is the code that solved my problem.
const serp = {
siteFetched: true,
};
let update = Object.keys(serp).reduce((acc, cur) => {
acc[`keywords.$.apifySerp.${cur}`] = serp[cur];
return acc;
}, {});

Why do I get array of nulls in my database? [duplicate]

This question already has answers here:
Node.js Mongoose.js string to ObjectId function
(9 answers)
Closed 4 years ago.
I have an array of ids which is launchIds.
I'm trying to push it on a model field trips with
$addToSet: { trips: { $each: launchIds }. This gives me an error: Cast to [ObjectId] failed for value \"[\"1\",\"2\",\"3\"]\...
if I try to map through launchIds and convert to Mongoose.Shema.Types.ObjectId I get in the database trips: [null,null,null]
lauchIds = ['1','2','3']
async bookTrips({ launchIds }) {
let userId = "5bf7f7b3817119363da48403";
const mongoIds = launchIds.map(l => Mongoose.Schema.Types.ObjectId(l));
return this.store.User.findByIdAndUpdate(
{ _id: userId },
{
$addToSet: { trips: { $each: mongoIds } }
},
{ new: true }
);
}
Here's my model Schema:
const UserSchema = new Mongoose.Schema(
{
email: {
type: String,
required: true
},
token: String,
trips: [
{
type: Mongoose.Schema.Types.ObjectId,
ref: "trip"
}
]
},
{ timestamps: true }
);
I'm passing ids via grapql playground. Here's my mutation:
bookTrips: async (_, { launchIds }, { dataSources }) => {
console.log(launchIds);
// logs ['1','2','3']
console.log(typeof launchIds);
//Object
const results = await dataSources.userAPI.bookTrips({ launchIds });
console.log(results);
return { message: "hello" };
}
To convert a string or a number into mongo object use Mongoose.Types.ObjectId,
const mongoIds = launchIds.map(l => Mongoose.Types.ObjectId(l));
I was getting back an array of strings where this should be numbers
The solution:
My model (same as above):
const UserSchema = new Mongoose.Schema(
{
email: {
type: String,
required: true
},
token: String,
trips: [
{
type: Mongoose.Schema.Types.ObjectId,
ref: "trip"
}
]
},
{ timestamps: true }
);
crud API:
async bookTrips({ launchIds }) {
let userId = "5bf7f7b3817119363da48403";
const idsToNums = launchIds.map(Number);
const mongoIds = idsToNums.map(l => Mongoose.Types.ObjectId(l));
return this.store.User.findByIdAndUpdate(
{ _id: userId },
{
$push: { trips: { $each: mongoIds } }
},
{ new: true }
);
}
Notice the Mongoose.Schema.Types.ObjectId on model and Mongoose.Types.ObjectId on api. If I remove Schema from model or add Schema to api I'm getting an error. Not sure why, but the above example works. I hope someone will find this helpful or suggests a better solution.

Cast to ObjectId failed for value at path _id for model with getAll during populate

I am trying to make a list of permissions for a role,
here's what I am trying to do in my permissions,
const PermissionsSchema = new mongoose.Schema({
name: {
type: String,
index: true,
required: true,
},
createdAt: {
type: Date,
default: Date.now
}
});
PermissionsSchema.statics = {
get(id) {
return this.findById(id)
.exec()
.then((permission) => {
if (permission) {
return permission;
}
const err = new APIError('No such permission exists!', httpStatus.NOT_FOUND);
return Promise.reject(err);
});
},
list({ skip = 0, limit = 50 } = {}) {
return this.find()
.sort({ createdAt: -1 })
.skip(+skip)
.limit(+limit)
.exec();
}
};
module.exports = mongoose.model('Permission', PermissionsSchema);
and this in my roles model.
const RoleSchema = new mongoose.Schema({
name: String,
type: String,
permissions: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Permission'
}],
createdAt: {
type: Date,
default: Date.now
}
});
RoleSchema.statics = {
get(id) {
// const _id = mongoose.Types.ObjectId.fromString(id);
return this.findById(id)
// .populate('permissions')
.exec()
.then((role) => {
if (role) {
return role;
}
const err = new APIError('No such role exists!', httpStatus.NOT_FOUND);
return Promise.reject(err);
});
},
list({ skip = 0, limit = 50 } = {}) {
return this.find()
.populate('permissions')
.sort({ createdAt: -1 })
.skip(+skip)
.limit(+limit)
.exec();
}
};
module.exports = mongoose.model('Role', RoleSchema);
and when I try to get all, I get this error
Cast to ObjectId failed for value "ADD_USER" at path "_id" for model "Permission"
I've gone through some other posts but they all say I need to pass _id as a string, but I am not querying myself, how would I cast _id?
So I already had some documents in my collection which didn't have any kind of ID in them.

Meteor collection2 does not validate on the client side

I am using collection2 with meteor to set default values. However when i run the method Meteor.call('commands.insert', {}) on the client, it just sets new document's ID, and only when the result from server comes it replaces the document with the right value. Actually, autoValue function runs on client because when i console.log there it logs (also tried defaultValue), but it does not do anything, does no modifications, nor unique: true is working, any property specified in the schema
server
export const Commands = new Mongo.Collection('commands')
Commands.schema = new SimpleSchema({
designation: {
type: String,
autoValue: function() {
console.log("inssssssssssssssssssseeeeeeeeeeeeeeeeeeeeeeert")
if (this.isInsert) {
return "Untitled"
}
},
unique: true
},
name: {
type: String,
autoValue: function() {
if (this.isInsert) {
return ""
}
},
optional: true
},
syntax: {
type: String,
autoValue: function() {
if (this.isInsert) {
return ""
}
},
optional: true
},
description: {
type: String,
autoValue: function() {
if (this.isInsert) {
return ""
}
},
optional: true
},
features: {
type: String,
autoValue: function() {
if (this.isInsert) {
return ""
}
},
optional: true},
type: {
type: String,
autoValue: function() {
if (this.isInsert) {
return ""
}
},
optional: true
},
variants: {
type: Array,
autoValue: function() {
if (this.isInsert) {
return []
}
},
},
'variants.$': {type: String}
})
Commands.attachSchema(Commands.schema)
Meteor.methods({
'commands.insert'(command) {
if (!this.userId) {
throw new Meteor.Error('not-authorized')
}
Commands.insert(command)
}
})
client
const setNewHandler = this.props.page.animationFinished ?
this.props.page.editing ?
textEditorData.length ?
() => {
Meteor.call(
'commands.update',
textEditorData[0]._id,
{
designation:
this.childComponents[0].editableContentNode.textContent,
name:
this.childComponents[1].editableContentNode.textContent,
syntax:
this.childComponents[2].editableContentNode.textContent,
type:
this.childComponents[3].editableContentNode.textContent,
variants:
this.childComponents[4].editableContentNode.textContent.split("\n"),
description:
this.childComponents[5].editableContentNode.textContent,
features:
this.childComponents[6].editableContentNode.textContent
}
)
} :
null :
() => {
Meteor.call('commands.insert', {})
} :
null

Updating array of objects in mongodb

I'm trying to update an array of objects in my simple-schema. Currently, it removes everything in the database and leaves behind:
"careerHistoryPositions": []
My simple-schema looks like:
const ProfileCandidateSchema = new SimpleSchema({
userId: {
type: String,
regEx: SimpleSchema.RegEx.Id
},
careerHistoryPositions: { type: Array, optional: true },
'careerHistoryPositions.$': { type: Object, optional: true },
'careerHistoryPositions.$.uniqueId': { type: String, optional: true },
'careerHistoryPositions.$.company': { type: String, optional: true },
'careerHistoryPositions.$.title': { type: String, optional: true }
});
If console.log form data looks like:
careerHistoryPositions: [Object, Object],
0: Object
company: "Test company"
title: "Test Title"
uniqueId: 1498004350350
1: Object
company: "Test company 2"
title: "Test Title 2"
uniqueId: 149800433221
My update function:
handleFormSubmit(event) {
event.preventDefault();
const { careerHistoryPositions } = this.state;
ProfileCandidate.update({ _id: this.state.profileCandidateCollectionId },
{ $set: {
careerHistoryPositions
}
}
);
}
I managed to fix this by mapping over my object and running 2 separate updates. The first removes the old element and the second adds the updated version. I'm sure there is a better way to do this, however, this does seem to work.
handleFormSubmit(event) {
event.preventDefault();
const { careerHistoryPositions } = this.state;
ProfileCandidate.update({_id: this.state.profileCandidateCollectionId}, { $unset: {
'careerHistoryPositions': {}
}
})
const updatePosition = this.state.careerHistoryPositions.map((position) => {
ProfileCandidate.update({_id: this.state.profileCandidateCollectionId}, { $push: {
'careerHistoryPositions': {
company: position.company,
title: position.title,
uniqueId: position.uniqueId
}
}
})