I know that with mongoose we can alter array elements fields with the $ sintax like this:
Person.update({'items.id': 2}, {'$set': {
'items.$.name': 'updated item2',
'items.$.value': 'two updated'
}}, function(err) { ...
Is there an equivalent way to do it with feathersjs services? If posible, it would be even greater if I could either update or patch an array element field at the same time that I'm updating/patching other properties of the document to which the array pertain.
I believe we still need to make some changes to allow this.
Why? The Mongoose service patch doesn't do anything different than described above so something like
app.service('person').patch({
'items.$.name': 'updated item2',
'items.$.value': 'two updated'
});
Should work.
What about if I need to change a specific element of the array? Say, for example, the array has five elements and I need to edit the last of these elements (index 4). Sorry, it may be that my question is because of little understanding of mongoose itself, and thus it may not be featherjs related. But my application needs to update the last element of an array at the same time it changes another field of the object/document.
app.service('person').patch({
"field": "new value",
// How to edit the last element of this array?
'items.4.value': 'two updated'
});
I would say this is definitely a Mongoose/MongoDB question. The index based update should work already. Briefly searching for how to update the last element this Stackoverflow question is all I could find. You might have to implement your own hook that does this manually.
Yes, I agree, it's really not a feathers question. I will try to create that hook. If I can't get it to work I can always edit the arrray with a for/foreach statement and save the whole object to the database via the service.update() method. Even so, thanks everyone for giving me some guidelines on this issue.
@UlyssesAlves
This query would work for you if you want to updated nested array element
User.updateOne({username: req.user.username},{$set: {"username":username, "user_profile": [{"description":description}]}},function(err, user){
//console.log(user);
if (err) throw err;
res.redirect('profile');
});
Your schema should be like this
/ User Schema
var UserSchema = mongoose.Schema({
username: {
type: String,
index:true
},
email: {
type: String
},
password: {
type: String
},
member_id:{
type: String,
default: shortid.generate
},
friends:[
{
"member_id": String,
"friend_name": String,
"Profile_pic": String
}
],
friend_requests: [
{
"member_id": String,
"friend_name": String,
"profile_pic": String
}
],
user_profile: [userProfileSchema]
});
Hope this helps
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue with a link to this issue for related bugs.
Most helpful comment
Why? The Mongoose service
patchdoesn't do anything different than described above so something likeShould work.