Handling Monggose schema change handling from string to string Array - javascript

My current doc is like this
{
"_id" : ObjectId("55ece69df332eb0000d34e12"),
"parent" : "P1",
"hierarchy" : {},
"hidden" : false,
"type" : "xyz",
"name" : "Mike",
"code" : "M110",
"date" : ISODate("2015-09-07T01:21:33.965Z"),
"__v" : 3,
"job_id" : "ca50fdf0-6904-11e6-b9af-1b0ea5d7f792"
}
now i want to have job_id as array instead. So i changed the field type to array in model schema. Now when I try to update the existing docs with some changes.
Document before saving looks like this
{
"_id" : ObjectId("55ece69df332eb0000d34e12"),
"parent" : "P1",
"hierarchy" : {},
"hidden" : false,
"type" : "xyz",
"name" : "Mike",
"code" : "M110",
"date" : ISODate("2015-09-07T01:21:33.965Z"),
"__v" : 3,
"job_id" : ["ca50fdf0-6904-11e6-b9af-1b0ea5d7f792",
"f1f04a95-42fa-41e5-a2c6-89c52c9c63f2"
]
}
so when i call model.save() method i'm getting following error:
{ [MongoError: The field 'job_id' must be an array but is of type String in document {_id: ObjectId('55ece69df332eb0000d34e12')}]
name: 'MongoError',
code: 16837,
err: 'The field \'job_id\' must be an array but is of type String in document {_id: ObjectId(\'55ece69df332eb0000d34e12\')}' }
What is the best way to handle this??

Related

MongoDB - Finding the parent object based on a very nested property

I have a collection that consists of posts. Inside those post objects are properties about the post, one of which being an array of tags associated with the post. Inside the array of tags are more objects, each of which are the tags with a name property. I would like to get back all the posts from this collection which have a given tag in them based on the name of the tag.
Here is an example of a post object within the collection:
{
"_id" : ObjectId("5c6a0478cba09c148b497fc6"),
"tags" : [
{
"_id" : "5c69d974e05511106048780e",
"name" : "Food",
"text_color" : "#ffffff",
"bg_color" : "#02569b",
"createdAt" : "2019-02-17T22:00:20.143Z",
"updatedAt" : "2019-02-17T22:00:20.143Z",
"__v" : 0
},
{
"_id" : "5c69d95de05511106048780d",
"name" : "Drinks",
"text_color" : "#ffffff",
"bg_color" : "#0175c2",
"createdAt" : "2019-02-17T21:59:57.758Z",
"updatedAt" : "2019-02-17T21:59:57.758Z",
"__v" : 0
}
],
"title" : "Title of the post",
"body" : "body of the post",
"author_id" : ObjectId("5c5e0d3b647f12e949cbea1e"),
"author_name" : "garrett",
"likes_count" : 1,
"createdAt" : ISODate("2019-02-18T01:03:52.497Z"),
"updatedAt" : ISODate("2019-02-28T00:25:21.969Z"),
"__v" : 0,
"dislikes_count" : 0
}
Of course I have other post objects in this collection, some of which may have different tags. How can I get all posts with the food tag to be returned?
A basic find query will do the job here. Here's how it looks
const tagName = 'food;
db.posts.find({ 'tags.name': tagName }).then(console.log);

MongoDB update function doesn't work with Mongoose

I'm trying to insert a new field into a document in MongoDB, but the database has no changes after my query.
This is the single element of my database:
{
"_id" : ObjectId("5a9f5f4bb9ba6117b5551f7d"),
"userId" : "user123",
"name" : "Device zm3",
"category" : [
"pm10",
"pm25",
"temperature"
],
"__v" : 0}
I want to have something like this:
{
"_id" : ObjectId("5a9f5f4bb9ba6117b5551f7d"),
"userId" : "user123",
"name" : "Device zm3",
"category" : [
"pm10",
"pm25",
"temperature"
],
"data": 5
"__v" : 0}
I use this query:
Device.update({
'userId': 'user123'
}, {
$set: {
'data': 5
}
}, {
upsert: true,
}
I was trying with fields witch already exists in database such as "name" or "category", and in this case solution works.
If you are going to add a field with Mongoose, it should also be in your Mongoose schema. So you would have to add "data" to your Device schema if you want to use Mongoose. That's why fields already in the object/schema (like "name" or "category") work but new ones don't.

Node.js update element in MongoDB

I have the following Mongoose schema and model:
var deviceSchema = new Schema({
deviceId:String,
deviceName:String,
devicePlace:String,
socket : [{number: Number,name:String, state : Boolean, current: Number, image:Number,locked:Boolean,reserved:Boolean}]
});
I already have a device in my database with four sockets.
Here example!
This is original data.
{
"_id" : ObjectId("5626569006bc3da468bafe93"),
"deviceId" : "0013A20040B5769A",
"deviceName" : "device",
"devicePlace" : "place",
"__v" : 0,
"socket" : [
{
"_id" : ObjectId("5628bd83570be84e28879e2d"),
"number" : 0,
"name" : "name"
"state" : true,
"current" : 0
"image" : 0,
"locked" : false,
"reserved" : false,
}, ...
]
}
and I received data from client for update.
{
"_id" : ObjectId("5626569006bc3da468bafe93"),
"deviceId" : "0013A20040B5769A",
"__v" : 0,
"socket" : [
{
"_id" : ObjectId("5628bd83570be84e28879e2d"),
"number" : 0,
"name" : "new name!!!!!"
"state" : true,
"current" : 0
}, ...
]
}
Now I'm trying to update a specific socket's name in the database with the following command:
device.update({deviceId: newData.deviceId, "socket.number": newData.number}, {$set: {"socket.$.name": newData.name}})
newData is object that extracted from socket array in received data.
I want to just update first socket's name.
or if possible, I want to update every socket's name as received socket array.
But this does not seem to be working, but I get no error. Can someone pin point what I'm doing wrong?
Add the callback to the update statement to see the error trace.
device.update({deviceId:newData.deviceId,'socket.number':newData.number}
,{$set: {"socket.$.name" : newData.name}}
,function(error,updatedDevice){
if(error) throw error;
// or : console.log("update error",error.message);
})

Node.js update elements in MongoDB

I have the following Mongoose schema and model:
var deviceSchema = new Schema({
deviceId:String,
deviceName:String,
devicePlace:String,
socket : [{number: Number,name:String, state : Boolean, current: Number, image:Number,locked:Boolean,reserved:Boolean}]
});
I already have a device in my database with four sockets.
Here example!
This is original data.
{
"_id" : ObjectId("5626569006bc3da468bafe93"),
"deviceId" : "0013A20040B5769A",
"deviceName" : "device",
"devicePlace" : "place",
"__v" : 0,
"socket" : [
{
"_id" : ObjectId("5628bd83570be84e28879e2d"),
"number" : 0,
"name" : "name"
"state" : true,
"current" : 0
"image" : 0,
"locked" : false,
"reserved" : false,
}, ...
]
}
and I received data from client for update.
{
"_id" : ObjectId("5626569006bc3da468bafe93"),
"deviceId" : "0013A20040B5769A",
"__v" : 0,
"socket" : [
{
"_id" : ObjectId("5628bd83570be84e28879e2d"),
"number" : 0,
"name" : "new name!!!!!"
"state" : true,
"current" : 0
}, ...
]
}
Now I'm trying to update a specific socket's name in the database with the following command:
device.update({deviceId: newData.deviceId, "socket.number": newData.number}, {$set: {"socket.$.name": newData.name}})
newData is object that extracted from socket array in received data.
I want to just update first socket's name.
or if possible, I want to update every socket's name as received socket array.
But this does not seem to be working, but I get no error. Can someone pin point what I'm doing wrong?

Get all parent documents in a mongoDB model tree structure

I'm using a model tree structure for my collection. As references I'm using parent-fields. I need to get attributes from the current object and all its parents. The last element in a path has a field 'target'. So I start with
var result = parent = Articles.findOne({target: this.params._id});
do {
parent = Articles.findOne({_id: parent.parent}).parent;
for (var attrname in parent) { result[attrname] = parent[attrname]; }
}
while (parent.parent === null);
That seems to be very inefficient to me. Isn't it possible to do that with one line to get an object with all elements? Then I could process that object.
Example documents
{
"_id" : "LD6h5ZcDuJjexfKfx",
"title" : "title",
"publisher" : "public",
"author" : "author"
}
{
"_id" : "KSiyh8zHRq8RZQ2E6",
"edition" : "edition",
"year" : "2020",
"parent" : "LD6h5ZcDuJjexfKfx"
}
{
"_id" : "5yCk4y25wrLBLZhyY",
"pageNumbers" : "1-10",
"target" : "9sjhzPhyTuQ5Kbh6v",
"parent" : "KSiyh8zHRq8RZQ2E6"
}
So starting with "target" : "9sjhzPhyTuQ5Kbh6v" I would like to get the two parent documents (in this example).
At least I need the dataset
"title" : "title",
"publisher" : "public",
"author" : "author",
"edition" : "edition",
"year" : "2020",
"pageNumbers" : "1-10"
If you want to do this in a single query then you need to follow the array of ancestors pattern in Mongodb. Otherwise you need to recursively traverse the branches above the leaf node as you are doing. For hierarchies with low depth such as yours this is not a big penalty.
With an array of ancestors your doc tree would look like:
{
"_id" : "LD6h5ZcDuJjexfKfx",
"title" : "title",
"publisher" : "public",
"author" : "author",
}
{
"_id" : "KSiyh8zHRq8RZQ2E6",
"edition" : "edition",
"year" : "2020",
"ancestors" : ["LD6h5ZcDuJjexfKfx"],
"parent" : "LD6h5ZcDuJjexfKfx"
}
{
"_id" : "5yCk4y25wrLBLZhyY",
"pageNumbers" : "1-10",
"target" : "9sjhzPhyTuQ5Kbh6v",
"ancestors" : ["LD6h5ZcDuJjexfKfx","KSiyh8zHRq8RZQ2E6"],
"parent" : "KSiyh8zHRq8RZQ2E6"
}
To get the doc and its parents:
Articles.find({ $or: [ { target: target },
_id: { $in: Articles.findOne({ target: target }).ancestors }]});

Categories

Resources