Increasing one field in a MongoDB collection with Mongoose - node.js

I'm trying to increment a value in a collection in my MongoDB database through Mongoose. This is the demo code shown on the Mongoose website:
var conditions = { name: 'borne' }
, update = { $inc: { visits: 1 }}
, options = { multi: true };
Model.update(conditions, update, options, callback)
And I have something like this:
var conditions = { "uniqueId" : itemId };
var update;
if(increase)
update = {$inc : {inStock : 1}};
else
update = {$dec : {inStock : 1}};
Item.update(conditions, update, {}, callback);
As you can see there is not much difference from the Mongoose's website code.
The problem is that when this piece of code is executed, I end up having in my collection one field called $dec (or $inc) which has an object as a field in the form {inStock : 1}. I just would like to increment the inStock entry of the collection. In the Schema I have:
var ItemToSell = new Schema({
uniqueId : { type: Number, index: true }
, name : String
, type : String
, inStock : Number
});
Can anyone point out what am I doing wrong?
Thanks a lot.

A) Make sure you're Mongoose is up-to-date. Older versions were very buggy on Model.update operations because Mongoose attempts to infer when you are merely passing a new object, in which case it turns your update object into a $set operation.
B) Try removing the empty {} from your function call. It is optional, and by passing an empty object rather than actual options, you may be confusing Mongoose into setting the { safe: false } option, which could also be causing your problem. I have not checked the source code to confirm that that could be the issue, but it's probably worth a try.

Related

push all element of array in subdocument while saving document

I want to push elements of array to create subdocument,
my schema
var chatGroup = new Schema({
name : {
type : String,
default : null
},
members: {
type : [subSchemaForMember]
},
}, { collection: 'chatGroup' });
var subSchemaForMember = new Schema({
user_id : {type : Schema.Types.ObjectId , ref : 'user'}},{_id : false});
my query to save document is
var chatGroup = new ChatGroup({
name : req.body.name,
image : req.body.image,
created_by : req.body.celebrity_id,
$pushAll : {'members' : req.body.members}
})
where req.body.memebers = ['someid','someid','someid']
Please help I want to do it without any loop
I don't see you actually saving the document, only calling new on the constructor. You need to explicitly call save. on the object after you construct it. For the documentation on creating documents, see here: http://mongoosejs.com/docs/models.html.
Also, the use of $pushAll only applies when you have an object already in mongodb, which has existing values, and you want to retain those values and push additional values onto the array (so in your example you can simply assign the array to members).
Also of note is that the current mongoose documentation indicates that $pushAll is deprecated and you should be using $push together with $each, but the same rules apply, see here:
https://docs.mongodb.com/manual/reference/operator/update/push/#append-multiple-values-to-an-array

Defining a map with ObjectId key and array of strings as value in mongoose schema

I'm facing a problem while creating Mongoose schema for my DB. I want to create a map with a objectId as key and an array of string values as its value. The closest that I can get is:
var schema = new Schema({
map: [{myId: {type:mongoose.Schema.Types.ObjectId, ref: 'MyOtherCollection'}, values: [String]}]
});
But somehow this is not working for me. When I perform an update with {upsert: true}, it is not correctly populating the key: value in the map. In fact, I'm not even sure if I have declared the schema correctly.
Can anyone tell me if the schema is correct ? Also, How can I perform an update with {upsert: true} for this schema?
Also, if above is not correct and can;t be achieved then how can I model my requirement by some other way. My use case is I want to keep a list of values for a given objectId. I don't want any duplicates entries with same key, that's why picked map.
Please suggest if the approach is correct or should this be modelled some other way?
Update:
Based on the answer by #phillee and this, I'm just wondering can we modify the schema mentioned in the accepted answer of the mentioned thread like this:
{
"_id" : ObjectId("4f9519d6684c8b1c9e72e367"),
... // other fields
"myId" : {
"4f9519d6684c8b1c9e73e367" : ["a","b","c"],
"4f9519d6684c8b1c9e73e369" : ["a","b"]
}
}
Schema will be something like:
var schema = new Schema({
myId: {String: [String]}
});
If yes, how can I change my { upsert:true } condition accordingly ? Also, complexity wise will it be more simpler/complex compared to the original schema mentioned in the thread?
I'd suggest changing the schema so you have one entry per myId,
var schema = new Schema({
myId : {type:mongoose.Schema.Types.ObjectId, ref: 'MyOtherCollection'},
values : [String]
})
If you want to update/upsert values,
Model.update({ myId : myId }, { $set : { values : newValues } }, { upsert : true })

Mongodb prevent empty values while updating

I have a collection of words, the scheme is as follows:
var wordsSchema = new Schema({
name : { type : String , trim : true , required : true , unique : true , index: true},
definition : { type : String , trim : true , required : true }
});
when I try to save new word with empty name or definition into collection required: true works end return error,but when I try to update collection and set empty name or definition value required:true doesn't works and updated word with empty fields saves into collection I want to prevent saving empty words into collection. How can I achieve this with a shortest way, My Update code looks like this:
words.update({ _id : word._id }, { $set : {
name : word.name,
definition : word.definition
}
} , function(err,data) {
if(err) {
res.status(1033).send("There was error while changing word");
} else {
res.send('Word has successfully changed');
}
});
required:true is not something maintained at the database level, but rather mongoose itself handles that for you. when you do an update operation, mongoose doesn't run your validators (required:true is a type of validator).
There is a change coming up in mongoose 4 where validators get run on updates. For now, your options are
manually check if there's nothing there (enforced by your application)
do a find on the document, then edit the field and do doc.save which will run validators (enforced by mongoose)
add a document with an empty value for 'word'. because you have a unique index on that field, mongodb will not allow you to insert another document without a value for that field (enforced by mongodb)
I would recommend that last option.

$unset is not working in mongoose

My schema is as follows : -
var Schema1 = new mongoose.Schema({
name: String,
description: String,
version: [{
id: String,
status: Number
}]
});
I want to unset the version field. I try the following code :-
Schema1.update({}, {
$unset: {
version: 1
}
}, {
multi: true
}).exec(function(err, count) {
console.log(err, count)
});
It gives me the following output :-
null 10
But the output contain the version field :-
{
name : 'a',
description : 'sdmhf',
version : []
}
The above code remove the data but I want to remove the version field from my collection as well. Can you tell me how to do that?
There's nothing wrong with your code. Mongoose is actually deleting those fields in the documents (which I assume is what you expected). You can see by opening a mongo shell into your database and searching all your documents before and after the update (use db.yourcollection.find({}))
Why does an empty array still appear even when it's removed from every document in the collection? Mongoose will ensure the documents returned will obey the schema that you define. So even if Mongoose finds no version property pointing to an Array in the actual document, it will still present an empty array when the matching documents are returned.
You can verify this yourself by adding some arbitrary property (pointing to an Array) to your schema and running a .find({}) again. You'll see that Mongoose will return these properties in every document even though you never saved them to the database. Similarly, if you add non-Array properties like Strings, Booleans, etc, Mongoose will return those as long as you specify a default value.
If you want to drop version for good (as you mentioned in your comment) you can drop it from your Mongoose schema after you've completed the $unset.
This worked for me
doc.field = undefined
await doc.save()

find id of latest subdocument inserted in mongoose

i have a model schema as :
var A = new Schema ({
a: String,
b : [ { ba: Integer, bb: String } ]
}, { collection: 'a' } );
then
var M = mongoose.model("a", A);
var saveid = null;
var m = new M({a:"Hello"});
m.save(function(err,model){
saveid = model.id;
}); // say m get the id as "1"
then
m['b'].push({ba:235,bb:"World"});
m.save(function(err,model){
console.log(model.id); //this will print 1, that is the id of the main Document only.
//here i want to find the id of the subdocument i have just created by push
});
So my question is how to find the id of the subdocument just pushed in one field of the model.
I've been looking for this answer as well, and I'm not sure that I like accessing the last document of the array. I do have an alternative solution, however. The method m['b'].push will return an integer, 1 or 0 - I'm assuming that is based off the success of the push (in terms of validation). However, in order to get access to the subdocument, and particularly the _id of the subdocument - you should use the create method first, then push.
The code is as follows:
var subdoc = m['b'].create({ ba: 234, bb: "World" });
m['b'].push(subdoc);
console.log(subdoc._id);
m.save(function(err, model) { console.log(arguments); });
What is happening is that when you pass in the object to either the push or the create method, the Schema cast occurs immediately (including things like validation and type casting) - this means that this is the time that the ObjectId is created; not when the model is saved back to Mongo. In fact, mongo does not automatically assign _id values to subdocuments this is a mongoose feature. Mongoose create is documented here: create docs
You should also note therefore, that even though you have a subdocument _id - it is not yet in Mongo until you save it, so be weary of any DOCRef action that you might take.
The question is "a bit" old, but what I do in this kind of situation is generate the subdocument's id before inserting it.
var subDocument = {
_id: mongoose.Types.ObjectId(),
ba:235,
bb:"World"
};
m['b'].push(subDocument);
m.save(function(err,model){
// I already know the id!
console.log(subDocument._id);
});
This way, even if there are other database operations between the save and the callback, it won't affect the id already created.
Mongoose will automatically create an _id for each new sub document, but - as far as I know - doesn't return this when you save it.
So you need to get it manually. The save method will return the saved document, including the subdocs. As you're using push you know it will be the last item in the array, so you can access it from there.
Something like this should do the trick.
m['b'].push({ba:235,bb:"World"});
m.save(function(err,model){
// model.b is the array of sub documents
console.log(model.b[model.b.length-1].id);
});
If you have a separate schema for your subdocument, then you can create the new subdocument from a model before you push it on to your parent document and it will have an ID:
var bSchema = new mongoose.Schema({
ba: Integer,
bb: String
};
var a = new mongoose.Schema({
a: String,
b : [ bSchema ]
});
var bModel = mongoose.model('b', bSchema);
var subdoc = new bModel({
ba: 5,
bb: "hello"
});
console.log(subdoc._id); // Voila!
Later you can add it to your parent document:
m['b'].push(subdoc)
m.save(...

Resources