Remove an ObjectId from an array of objectId - javascript

I have an objectId like this:
["56153e4c2040efa61b4e267f","56033932efefe0d8657bbd9e"]
To save that information in my model I use:
items: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Items'
}]
What I'm trying to do is to pull an element of the array that is equal to objectId that I send from the front end in a delete request.
The code I'm using:
_.remove(unit.items, request.params.itemId);
I'm using lodash library.
The problem I suppose is that the array have ObjectId elements and I'm trying to compare with an string that is the request.params.itemId.

I have a very similar setup with an "Event" object that has an array of "Assignment" objects saved as an array of ObjectIds. I was able to simply use
obj.arrayField.remove(idToRemove);
Here is the relevant code inside of my delete route handler:
var id = req.assignment._id;
req.event.assignments.remove(id);
req.event.save(function(err, event) {
//etc
}
Does this work for you?
unit.items.remove(request.params.itemId);

You need to pass the string into mongoose.Types.ObjectId('') to get an actual object you can compare against.
So _.remove(unit.items, mongoose.Types.ObjectId(req.params.itemId));

Related

Find all realted matched docs in an array of string

I have a mongoose schema model that have a field name tags , and it is an array of strings to store some tags in it for each document. I want something for example if I have an array of tags like ["test", "testimonials", "test Doc"] tags in it, when i search for test, it returns all documents with tags that they are testimonials or test doc , it should be work for example like wildcards (test*) .... can anyone help ?
this is the model
tags: {
type: [
{
type: String,
},
],
},
First of all, I'd tweak the Schema if possible. Your schema could be changed to this:
tags: [String]
This also just means an array of strings. You don't need to always need to use/specify the type key unless you're planning to add more fields to the tag schema, but it doesn't look like it from the question.
You can do the following to select all documents with a specific tag. Since I don't know what the name of your model is, I'll just call it "Model".
await Model.find({ tags: "tagName" })
OR
await Model.find({ tags: { $elemMatch: { someKey: someValue } } })
The later is only if you have other mongodb documents inside the array. Since you only have strings in the array, use the first method.

Read data from JSON with multiple JSON objects in order to be displayed

I have the following JSON object that contains multiple JSON objects.
I want to read and display the following elements 1) CampaignName 2) Start date 3) End date
I have written the following the following code which produces error to the browser console. So, the items are not displayed.
the produced error at the browser console is:
I assume I do not access the elements as appropriate.
How shall I do it ?
You are using the .each function that iterate over each object... each object has the properties that you need. Each of these values you are iterating over is an object and not an array
Use v.Campaign.CampaignName instead of accessing the index first
the v that you are trying to access already is the date on a single JSON object so there is no need of passing the count param. I would suggest you refactoring your code to something like:
data.forEach(({ Campaign: {CampaignName, StartDate, EndDate } }) => {
events.push({
title: CampaignName,
title: moment(StartDate),
title: moment(EndDate),
})
})

Updating all fields in an document using a Javascript object

I want to update all the fields in a MongoDB document and I have a Javascript object that contains all these fields. I could easily type out each field to update but this seems like a lot of manual work and not reusable. I wanted to do something like below but this creates an object containing all the new field data within the document called newData.
I've tried JSON.stringify on the variable but the format isn't appropriate for update.
var newData = {
_id:ObjectId("53245234..."),
id: 88888,
firstData: "someData",
secondData: 787855,
thirdData: [ 45,17,12,234]
};
var collection = db.get('CollectionToUpdate');
//strip out dB id so as not to overwrite it, possibly not needed
if ("_id" in newData) {
delete newData["_id"];
}
//find the correct document based on program generated id and update
collection.update({id: newData.id}, {
newData
})
If you trust newData will not have any keys you don't intend (like update operators) this should work:
var collection = db.get('CollectionToUpdate');
collection.update({id: newData.id}, newData)
Note that this replaces the document. I assume that is what you meant by "update all the fields". update does not replace "_id".
Documentation for update

Create/update objects with mongoose/mongoDB

The internet is full of resources for dealing with arrays, but often objects are a more natural fit for data and seemingly more efficient.
I want to store key-value objects under dynamic field names like this:
project['en-US'] = { 'nav-back': 'Go back', ... }
project['pt-BR'] = { 'nav-back': 'Volte', ... }
Doing this seems like it would be more efficient than keeping an array of all languages and having to filter it to get all language entries for a given language.
My question is: How can I insert a key-value pair into an object with a dynamic name using mongoose? And would the object need to exist or can I create it if it doesn't in one operation?
I tried this:
await Project.update(
{ _id: projectId },
{
$set: {
[`${language}.${key}`]: value,
},
});
But no luck regardless of if I have an empty object there to begin with or not: { ok: 0, n: 0, nModified: 0 }.
Bonus: Should I index these objects and how? (I will want to update single items)
Thanks!
In mongoose, the schema is everything. It describe the data you gonna read/store from the database. If you wanna add dynamically a new key in the schema it's gonna be hard.
In this particulary case I would recommend to use the mongodb-native-driver which is way more permissive about the data manipulation. So you could read the data in a specific format and dynamically add your field into it.
To resume my thought, how should your dynamic change happen :
Use mongodb-native-driver to insert the new key into the database data
Modify the mongoose schema you have in the code (push a new key into it)
Use mongoose to manipulate the data afterward
Do not forget to dynamically update your mongoose model or you won't read the new key at the next find.
I solved this using the original code snippet unchanged, but adding { strict: false } to the schema:
const projectSchema = new Schema({ ...schema... }, { strict: false });

Mongoose Array Push Fails

I have a Mongoose schema with, among other things, an array of objects like so:
multipleThings: [{
field1: String,
field2: String,
field3: String,
thingId : { type: ObjectId, default: ObjectId }
}]
In my code I do a .findOne, which returns my object. myObject.multipleThings is an Array[0] at this point. I simply want to push something to this array, so I do
myObject.multipleThings.push(anObjectICreated)
And I get
undefined is not a function
at DocumentArray.SchemaType.applySetters (.../node_modules/mongoose/lib/schematype.js:570:26)
at Array.MongooseArray.mixin.push (.../node_modules/mongoose/lib/types/array.js:292:27)
at {The location of .push above in my code}
I don't understand what is stopping me from being able to push to the array?
I am still new to this as well put may I suggest you try myObject.multipleThings[0].push(anObjectICreated)

Categories