i have there a problem with mongoose & update documents.
when i upate a object in a collection then it "clear/drop" the object, and fill it with the to update object. But i need to "add/merge" the objects.
As Example:
Model.update({name: "hello"}, {
name: "hello",
datum: {
updated: Date.now(),
//added: Date.now()
}
}, function(err, data){
console.log(err, data);
});
This replace my "datum" object with on field: "updated.
The "added" filed is deleted. WHY ?
How can i update the nested "datum" object ?
You need to use the $set operator. If you don't specify it, the first document that matches your query document (1st parameter) will get replaced by your update document (2nd parameter) :
Model.update({name: "hello"}, {
$set: {
"datum.updated": Date.now()
}
}, function(err, data){
console.log(err, data);
});
Related
I want to query a document. here's its schema
{
_id,
notes: [{_id: 243234,
text: "hey"},
_id, 421123,
text: "hi"}
]
}
I want to first find the document by _id and then find the value of 'text' on notes[1].
Using this, I can find the actual document but how can I find the object inside notes array? I have to find and update the 'text' inside note.
socket.on("individualnote edit", function(data) {
rooms.find({ _id: data.roomId}, function( err, doc) {
if (err) {
console.log("Something wrong when updating data!");
}
console.log(doc);
});
You can use positional $ operator to find and update an element within a sub document array.
The positional $ operator identifies an element in an array to update without explicitly specifying the position of the element in the array.
rooms.findOneAndUpdate({
_id: _id,
'notes.text': 'hey'
}, {
'$set': {
'notes.$.text': 'new text'
}
}).then(() => {
console.log('Success');
}).catch((err) => {
console.log('err', err.stack);
});
I have a mongoose query like this:
var query = Events.findOneAndUpdate({ '_id': event._id,'participants._id':participant._id},{'$set': {'participants.$': participant}}, {upsert:false,new: true},function(err,result){
if(err){
return res.status(500).jsonp({
error: 'Unable to update participant'
});
}
console.log(result.participants[0]);
res.jsonp(result.participants[0]);
});
and the query works properly modifying the participants subdocument inside Events collection.
The problem:
I need only the modified participant to be returned as JSON and I am not in need of the entire participants array but I am not able to achieve this since I get all the participants when I do console.log(result.participants);
How do I get only the modified subdocument after the query?
You may have to use the native JS filter() method as in the following:
Events.findOneAndUpdate(
{ '_id': event._id, 'participants._id': participant._id },
{ '$set': { 'participants.$': participant } },
{ upsert: false, new: true },
function(err, result){
if(err){
return res.status(500).jsonp({
error: 'Unable to update participant'
});
}
var modified = result.participants.filter(function(p){
return p._id === participant._id
})[0];
console.log(modified);
res.jsonp(modified);
}
);
I'm getting a duplicate document when using the mongodb-native-driver to save an update to a document. My first call to save() correctly creates the document and adds a _id with an ObjectID value. A second call creates a new document with a text _id of the original ObjectID. For example I end up with:
> db.people.find()
{ "firstname" : "Fred", "lastname" : "Flintstone", "_id" : ObjectId("52e55737ae49620000fd894e") }
{ "firstname" : "Fred", "lastname" : "Flintstone with a change", "_id" : "52e55737ae49620000fd894e" }
My first call correctly created Fred Flinstone. A second call that added " with a change" to the lastname, created a second document.
I'm using MongoDB 2.4.8 and mongo-native-driver 1.3.23.
Here is my NodeJS/Express endpoint:
app.post("/contacts", function (req, res) {
console.log("POST /contacts, req.body: " + JSON.stringify(req.body));
db.collection("people").save(req.body, function (err, inserted) {
if (err) {
throw err;
} else {
console.dir("Successfully inserted/updated: " + JSON.stringify(inserted));
res.send(inserted);
}
});
});
Here is the runtime log messages:
POST /contacts, req.body: {"firstname":"Fred","lastname":"Flintstone"}
'Successfully inserted/updated: {"firstname":"Fred","lastname":"Flintstone","_id":"52e55737ae49620000fd894e"}'
POST /contacts, req.body: {"firstname":"Fred","lastname":"Flintstone with a change","_id":"52e55737ae49620000fd894e"}
'Successfully inserted/updated: 1'
Why doesn't my second update the existing record? Does the driver not cast the _id value to an ObjectID?
What you are posting back the 2nd time contains a field named "_id", and it's a string. That is the problem.
Look at the document, what the save method does is a "Simple full document replacement function". I don't use this function quit often so here's what I guess. The function use the _id field to find the document and then replace the full document with what you provided. However, what you provided is a string _id. Apparently it doesn't equal to the ObjectId. I think you should wrap it to an ObjectId before passing to the function.
Besides, the save method is not recommended according to the document. you should use update (maybe with upsert option) instead
I don't exactly know why a second document is created, but why don't you use the update function (maybe with the upsert operator)?
An example for the update operation:
var query = { '_id': '52e55737ae49620000fd894e' };
db.collection('people').findOne(query, function (err, doc) {
if (err) throw err;
if (!doc) {
return db.close();
}
doc['lastname'] = 'Flintstone with a change';
db.collection('people').update(query, doc, function (err, updated) {
if (err) throw err;
console.dir('Successfully updated ' + updated + ' document!');
return db.close();
});
});
And now with the upsert operator:
var query = { '_id': '52e55737ae49620000fd894e' };
var operator = { '$set': { 'lastname': 'Flintstone with a change' } };
var options = { 'upsert': true };
db.collection('people').update(query, operator, options, function (err, upserted) {
if (err) throw err;
console.dir('Successfully upserted ' + upserted + ' document!');
return db.close();
});
The difference is that the upsert operator will update the document if it exist, otherwise it will create a new one. When using the upsert operator you should keep in mind that this operation can be underspecified. That means if your query does not contain enough information to identify a single document, a new document will be inserted.
I'm using MongoDB in node.js
What I would like is to upsert a document in a collection. The document has an unique ID, a lastAccess field, which stores the date of the last time accessed, and a timesAccessed field, which should be set to 0 on document creation and incremented by 1 if updating.
I tried:
// coll is a valid collection
coll.update(
{user: accountInfo.uid},
{user: accountInfo.uid,
lastAccess: new Date(),
$inc: {timesAccessed: 1},
$setOnInsert: {timesAccessed: 0}
},
{upsert: true, w: 1},
function(err, result) {
if (err) throw err;
console.log("Record upserted as " + result);
});
but node says:
MongoError: Modifiers and non-modifiers cannot be mixed
What is a coincise and safe way to do this?
You should either $set the values or update/replace the whole object. So either update(find_query, completely_new_object_without_modifiers, ...) or update(find_query, object_with_modifiers, ...)
Plus, you cannot $set and $setOnInsert with the same field name, so you will start counting from 1 :) Oh, and you don't need to add the find_query items to the update_query, they will be added automatically.
Try:
col1.update( {
user: accountInfo.uid
}, {
$set: {
lastAccess: new Date()
}
$inc: {
timesAccessed: 1
}
}, {
upsert: true,
w: 1
}, function(err, result) {
if(err) {
throw err;
}
console.log("Record upsert as", result);
});
I would like to retrieve some data from a Mongoose setting in my Node.js application. I noticed that no matter what I write as field selection, I always get the _id field. Is there a way not to fetch it?
This is how I do right now:
Transaction.find({username : user.username}, ['uniqueId', 'timeout', 'confirmation_link', 'item_name'], function(err, txs){
console.log("user : " + user.username + " with txs: " + txs);
callback(txs);
});
And logs me the results which contain the _id field.
Another way is to use text argument with prefix - which will exclude this or that field from the result:
Entity.find({ ... }, '-_id field1 field2', function(err, entity) {
console.log(entity); // { field1: '...', field2: '...' }
});
_id must be specifically excluded. For example,
Transaction.find({username : user.username}, { '_id': 0, 'uniqueId' :1, 'timeout': 1, 'confirmation_link': 1, 'item_name': 1}, function(err, txs){
console.log("user : " + user.username + " with txs: " + txs);
callback(txs);
});
Another approach:
Augment the .toJSON() of the schema that it deletes the _id and the __v fields
Call .toJSON() on all DB objects sent to client
Extra benefit #1: you can use item.id === 'something' because typeof id === 'string', not ObjectId.
Extra benefit #2: When you got gan object back from the client and you want to search / update then you don't have to manually delete _id because there is none, just an id which is ignored.
Augmenting JSON:
mySchema.set('toJSON', {
virtuals: true,
transform: (doc, ret, options) => {
delete ret.__v;
ret.id = ret._id.toString();
delete ret._id;
},
});
So you can use:
let item = (await MyCollection.findOne({/* search */}).exec()).toJSON();
if (item.id === 'someString') return item;
I know it's ugly. But it's the best bad idea that I have so far.
In 5.2.13 version of Mongoose (Sept 2018)- using the query builder approach the same can be converted to
async function getUserDetails(user) {
try {
if (!user || !user.name) return;
const result = await Transaction.
find({username : user.username}).
select('uniqueId timeout confirmation_link item_name -_id');
// Adding minus sign before the _id (like -_id) in the select string unselects the _id which is sent by default.
console.log(result);
} catch(ex) {
return ex
}
}
The easiest thing you can do is something like this:
Transaction.find({username : user.username}, {_id: 0}, (err, txs) => {
// the return document won't contain _id field
// callback function body
}
Just remember that in the second object passed in the find()-
Pass 0 as the value to the specific key that you wish not to fetch
from the mongodb database.
Pass 1 as the value when you wish to
fetch from the mongodb database.