How to find a document from mongodb using mongoose based on query and then insert some data to it and save back? - mongodb

I have my Model as
var Model = {"name":String,"email":String,"notes":[{"time":Date,"title":String,"description":String}]
And I want to find document based on the email, and then add a note to the array. And then save it back.
What I tried is,
var updatedNote = {};
Model.findOne({'email':'test#test.com'},function(err, note){
for(var property in note._doc){
if(note._doc.hasOwnProperty(property)){
updatedNote[property] = note._doc[property];
};
}
updatedNote.notes.push(newNote);
note._doc = updatedNote;
note.save(function(err){
if(err){
console.log(error);
}
else {
res.redirect('/notes');
}
})
});
But it is throwing error as "Object does not have save method". I don't want to use findByIdAndUpdate() as i am leaving this responsibility of generating id on mongo.

I don't understand what most of that code is doing. If I wanted to add a note to the document (I'm assuming newNote is defined elsewhere), I'd just do:
Model.findOne({'email':'test#test.com'},function(err, note){
note.notes.push(newNote);
note.save(function(err){});
});

Related

ObjectId as key to another collection-Migration

I am trying to add the ObjectId as a "Foreign key" to a collection. I have the previous id to link but I am having problem with the script.
Following is the script
db.users.find().forEach(function (user) {
var cursor = db.po1.find({"owner:": user.ID});
cursor.forEach(function(property) {
property.user_id = user._id;
db.po1.save(property);
});
});
The script runs but I do not get the field added to the documents of the po1 collection.
I am using mongoose for the api so I need the ObjectId. I do not want to embed the documents because of the rarity of the calls and the size of the po1 per user.
user.ID and po1.owner field are of the same type.
Thanks you for your time
From comment the answer.
Although save() has also been deprecated and finally the bellow script did the trick
db.users.find().forEach(function (user) {
var cursor = db.views.find({"user": user.ID});
cursor.forEach(function(object) {
object.userId = user._id;
db.views1.insertOne(object);
});
});
So through the innsert I created new collection and dropped previous.

Why i can't replace field in mongoose document?

vk_account.settings is an Array in mongoose schema.
vk_account.save(function(err, vk_account) {
if(err) return cb(err, null);
vk_account.Sources = updated_sources;
vk_account.settings = account_setting;
cb(null, vk_account);
})
I want to replace vk_account.settings(Array) to one certain object from the vk_account.settings, which is account_setting(Object), but when I replace it, it does not get replaced and vk_account.settings as before has old value.
As I understand it, the mongoose prohibits and does not assign an Object to a variable of type Array, but I don't want to save it, I just want to send it to the client and forget.
Firstly you cannot assign same value for save as well as for response vk_account... Then you have to change the instance to object using toObject() and then you can add keys in it
vk_account.save(function(err, vk) {
if(err) return cb(err, null);
var object = vk.toObject();
vk.Sources = updated_sources;
vk.settings = account_setting;
cb(null, vk);
})

Overwrite object in mongodb

This should be simple but it is surprisingly difficult and extremely frustrating. I am trying to overwrite an 'Object' field in mongodb with a new Object that the user creates in my client webpage. I have validated that all other fields I am passing to the update operation are in fact being updated, with the exception of the javascript object. Instead of it updating with the object I am passing (While I validated is being populated with the object I am passing through), it just updates it back to {} instead of whats being passed:
{ nodes:[ { w: 120, h: 80,type: 'InHive',left: 184,top: 90,text: 'item',query: 'hey',name: 'sample',id: '7686132d-6fcf-4a3b-baa2-b1c628e0b2d6' } ], edges: [], ports: [],groups: [] }
When I attempt to update the data field outside of the meteor method, directly from the mongo console interface, it overwrites that field successfully with the javascript object. What am I doing wrong here, because I cant for the life of me figure this one out?
Server Method
'updateOneWorkflow': function(id, field, object) {
this.unblock;
if (Meteor.userId()) {
var _username = Meteor.user().username;
MYCOLLECTION.update({
_id: id
}, {
$set: {
[field]: object, //this just gets reset back to {} whenever this update method is called
"metadata.last_modified_dt": new Date(), //this gets updated
"metadata.modified_by": Meteor.userId(), //this gets updated
'metadata.modified_by_username': _username //This gets updated
}
});
} else {
throw new Meteor.Error(403, "You are not authorized to perform this function");
}
}
Client Call:
var _jsonformat = toolkit.exportData();
var currentid = Session.get('rulesRowClicked')._id;
console.log(_jsonformat);
Meteor.call('updateOneWorkflow' , currentid, 'data', _jsonformat, function(err, res){
if(err){
toastr.error('Failed to save result ' + err);
}
else{
toastr.success('Saved workflow');
}
});
I believe your problem is stemming from this line: [field]: object. I don't believe that's a proper method of dynamically accessing an object's field. Instead, try to dynamically update the field as so:
'updateOneWorkflow': function(id, field, object) {
this.unblock;
if (Meteor.userId()) {
var _username = Meteor.user().username;
var newObj = {
"metadata": {
"last_modified_dt": new Date(),
"modified_by": Meteor.userId(),
"modified_by_username": _username
}
};
newObj[field] = object;
MYCOLLECTION.update({
_id: id
}, {
$set: newObj
});
} else {
throw new Meteor.Error(403, "You are not authorized to perform this function");
}
}
The issue was crazier than I expected. If you are using Meteorjs and you are using the Aldeed Schema 2 collection framework, it seems to completely ignore updates/inserts of json objects even if you set the field type to Object, unless you set up the exact same schema as the object (including nested array objects) and attach it to your collection. Dumbest thing Ive ever seen, no idea why nothing warns you of this. I removed the schema attachment and it worked.

Data not being delete from elasticsearch index via mongoosastic?

I have mongoosastic setup within a MEAN stack program. Everything works correctly except when I delete a document from mongodb it is not deleted in the elasticsearch index. So every time I do a search that includes delete items, the deleted item is returned but is null when it is hydrated. Does mongoosastic handle deleting from the ES index? Do I have to program an index refresh?
var mongoose = require('mongoose');
var mongoosastic = require("mongoosastic");
var Schema = mongoose.Schema;
var quantumSchema = new mongoose.Schema({
note: {
type: String,
require: true,
es_indexed: true
}
});
quantumSchema.plugin(mongoosastic);
var Quantum = mongoose.model('Quantum', quantumSchema);
Quantum.createMapping(function(err, mapping){
if(err){
console.log('error creating mapping (you can safely ignore this)');
console.log(err);
}else{
console.log('mapping created!');
console.log(mapping);
}
});
I had the same error. If you look in the Documentation it states that you have to explicit remove the document after deleting it.
This is the way i am doing a deletion now.
const deleteOne = Model => async (id)=> {
const document = await Model.findByIdAndDelete(id);
if (!document) {
return new Result()
.setSuccess(false)
.setError('Unable to delete Entity with ID: ' + id + '.')
}
//this ensures the deletion from the elasticsearch index
document.remove();
return new Result()
.setSuccess(true)
.setData(document)
}
I dont know what version of mongoosastic you're using but i use mongoosastic#3.6.0 and my indexed doc get deleted whenever i remove it either using Model.findByIdAndRemove or Model.remove. Therefore try to cross check the way you delete you're docs.
I solved the problem by changing the way I delete the data.
I was using:
Quantum.findByIdAndRemove(quantumid)
I switched it to:
Quantum.findById(quantumid, function(err, quantum) {
quantum.remove(function(err, quantum) {
if (err) {
console.log(err);
return;
}
});
});
I did not research the reason for this working, but it solved the problem and I moved on.

getting values from WriteResult mongo

I was trying to get familiar with the WriteResult object in mongo, but I can't access any of its values. The docs say the number of values inserted is stored in WriteResult.nInserted. Trying to access nInserted is crashing my server.
var readings = new Readings({
val1: parseInt(Data[0]),
val2: parseInt(Data[1]),
val3: parseInt(Data[2]),
val4: parseInt(Data[3]),
val5: parseInt(Data[4]),
val6: parseInt(Data[5]),
})
var result = readings.save(function (err, post){
if(err){return next(err)}
res.status(201).json(readings)
})
if(result.nInserted > 0){
console.log('wrote to database')
}
else{
console.log('could not write to database')
}
I know the data is being written to the database. I see it in the mongo shell.
The save method on a model instance doesn't return anything. All results are reported via the callback method, so you'd use something like this:
readings.save(function (err, doc, numberAffected){
if(err){return next(err)}
if (numberAffected > 0) {
console.log('updated an existing doc');
} else {
console.log('added a new doc');
}
res.status(201).json(doc)
})
Mongoose doesn't give you access to the full WriteResult, but as long as err is null you can rest assured the save succeeded and it's only a matter of whether an existing doc was updated or a new one was added. Because you're creating a new doc here, numberAffected will always be 0.