This is my Schema in Model.
const applicantEvaluationSchema = new mongoose.Schema(
{
applicantIdx: Number,
application: {
comments: [
{
userIdx: Number,
comment: String,
createdAt: Date,
},
],
evaluations: [
{
userIdx: Number,
point: Number,
},
],
},
interview: {
comments: [
{
userIdx: Number,
comment: String,
createdAt: Date,
},
],
evaluations: [
{
userIdx: Number,
point: Number,
},
],
},
}
);
I wanna push comment in application.comments
I got the idea that clone the Array, push my comment and update it
but I think There's the better way to push the object.
How can I solve it?
You can use Model.update with the $push operator:
//Your model
ApplicantEvaluation.update(
{ /* selection criteria */ },
{
$push: {
'application.comments': /* new comment object */
}
}
);
With the $push operator, you supply a field to push to and the new object. If you have a nested field, use dot syntax to access the field. Since the comments array is nested inside application use 'application.comments'.
Related
I have two schemas.
// tutorial
export const TutorialSchema = new mongoose.Schema({
title: String,
author: String,
tags: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Tag"
}
]
})
// tag
export const TagSchema = new mongoose.Schema({
name: String,
companyId: Number
})
constructor(#InjectModel('Tutorial') private readonly _tutorialModel: Model<any>) { }
I want to get count of tags for each tutorial (in one query). How can I do that ?
I know how to get list of tutorial.
const result = await _tutorialModel.find()
You can use group aggregation in the following way -
_tutorialModel.aggregate([
{
$project: {
title: 1,
_id:1,
numberOfTags: { $cond: { if: { $isArray: "$tags" }, then: { $size: "$tags"
}, else: "NA"} }
}
}
] )
For Size operator you need to ensure first that tags is always an array! If for any reason tags is not present then error will be thrown.
If you make sure tags will be always present and is an array then you can simplify to following -
_tutorialModel.aggregate([
{
$project: {
title: 1,
_id:1,
numberOfTags: {$size: "$tags"}
}
}
] )
Take a look at -
Size aggregation operator -
https://www.mongodb.com/docs/manual/reference/operator/aggregation/size/
This is my schema,
const courseSchema = new mongoose.Schema({
name: String,
code: String,
class: String,
credit: Number,
overview: String,
prerequisite: String,
syllabus: [
{
moduleName: String,
moduleDetails: String,
},
],
materials: [
{
moduleNo: Number,
moduleMaterials: [String],
},
],
teacher: String,
students: [String],
});
I want to add new materials in which each time an update operation is called I receive a
moduleNo and a materialURL.
I want to add this to the materials array in my existing course which is filtered by courseID. So each time I receive a moduleNo and a materialURL, I want to check if moduleNo already exists in the materials array. If yes, then add materialURL into the moduleMaterials array without deleting the existing urls in moduleMaterials. If no, then add a new object with moduleNo and moduleMaterials and materialURL pushed into moduleMaterials. I've heard about upsert and think that could be used but I'm not sure what the correct queries are to do this operation.
What I've currently come up with even though it's wrong,
Course.updateOne(
{ _id: courseID },
{
$push: {
materials: { moduleNo, moduleMaterials: { $push: { materialURL } } },
},
},
{ upsert: true },
(err, result) => {
if (err) {
console.error(err);
} else {
console.log(result);
}
}
);
How do I do execute this query?
I have some simple user data. Here is example for one user:
const userSchema = new Schema({
userName: {
type: String,
},
projectsInput: [
{
type: Schema.Types.ObjectId,
ref: "Project",
},
],
projectsHold: [
{
type: Schema.Types.ObjectId,
ref: "Project",
},
],
});
I want by having ProjectId to be able to remove all records from all users that contains it.
if I get the first one
60f02d21159c4b4110f21a32
how I can perform updateMany function for my UserModel?
return UserModel.updateMany(
{
projectsInput: {
$elemMatch: args.projectId,
},
},
{
projectsInput: {
$slice: [projectsInput.$, 1],
},
}
);
})
Here is my code that is not working.
args.projectId = 60f02d21159c4b4110f21a32 (my id for the project I want to delete)
and UserModel is my mongodb Schema for user.
you can use $pull
{
$pull: {
projectsInputs: "123"
}
}
Heres what my mongoose schema looks like-
const GameLogSchema = new Schema({
_score: Number,
_playerData: {
x: Number,
y: Number,
},
_zoneData: [{ _x: Number, _height: Number }],
_pipeData: [{ _x: Number, _randomeHeightTop: Number }],
_gap: Number,
});
const PlayerSchema = new Schema({
/* other fields */
_gameLogs: {
type: [[GameLogSchema]],
},
});
This is what the data its supposed to deal with looks like -
Spreading one of those objects -
How to push an array of objects having arrays, into an array ? preferably in nodejs mongoose.
EDIT -
I tried to do something similar to whats given in Mongodb $push in nested array
I tried this with my schema -
const PlayerSchema = new Schema({
/* other fields */
_gameLogs: [
{
_logs: [{ _log: { _score: Number } }],
},
],
});
And heres my update function -
Player.findOneAndUpdate(
{ \* filter *\ },
{
$push: {
/* pushing something other, that works */
_gameLogs: {
'_gameLogs.$._logs': {
'_logs.$._log': { '_log.$._score': req.body.gameLogs.score },
},
},
},
$inc: { _totalGamesPlayed: 1, '_gameStreak._gamesPlayed': 1 },
},
{ safe: true, upsert: true, new: true, minimize: false },
(err, result) => {
console.log(result);
}
);
It outputs a list of { _logs: [], _id: 5f4f5979fba2d03c40d4aed7 }, among other things.
I have a a schema as follows:
/**
* Answer Schema
*/
var AnswerSchema = new Schema({
answer: Number,
owner_id: Schema.Types.ObjectId
});
/**
* Poll Schema
*/
var PollSchema = new Schema({
question: { type: String, required: true, trim: true },
choices: [ { type: String, required: true, trim: true} ],
answers: [AnswerSchema]
});
How do I set an answer for a given poll_id and the owner_id of the person answering the poll?
The term "set or create" sort of opens this up a bit.
Essentially you will add (create) new items in arrays using the $push operator with .update(), or otherwise with a standard JavaScript array push once you have the current document after a .find().
But considering you might want to "update" an existing answer for a given owner then it's possibly a two step operation. If not then you just want the "update" using the $push.
PollSchema.update(
{ "_id": poll_id, "answers.owner_id": owner_id }
{ "$set":{ "answers.answer": value } },
function(err,numAffected) {
if (err)
throw err; // or whatever handling
// If this didn't modify anything then $push a document
if ( numAffected != 0 ) {
PollSchema.update(
{ "_id": poll_id },
{ "$push": {
"answers": {
"owner_id": owner_id,
"answer": value
}
}},
function(err, numAffected) {
// more things in here
}
);
}
);
Or again, if you do not care about having more than one answer per "owner" then just use the $push update.