I have a simple user model:
{
_id: "59d72070d9d03b28934b972b"
firstName: "first"
lastName: "last"
email: "first.last#gmail.com"
subscriptions: {
newsletter: true,
blog: true
}
}
I'm trying to do partial updates on the subscriptions object. I'm passing the id of the user and a payload object that can have either one or both properties of the object. Let's say I only want to update newsletter and set it to false. I'll send:
{ id: "59d72070d9d03b28934b972b", payload: { newsletter: false } }
And then:
const user = await User.findByIdAndUpdate(
args.id,
{ $set: { subscriptions: args.payload } },
{ upsert: true, new: true }
);
This will return:
subscriptions: {
newsletter: false
}
Is there a way to only modify the newsletter property when I only pass newsletter in the payload object without deleting the other properties? I know I only have two properties in this example, but in time, the object will keep expanding.
To update only the nested field, use { "subscriptions.newsletter": false } :
const user = (await User.findByIdAndUpdate(
args.id, {
$set: {
"subscriptions.newsletter": args.payload
}
}, {
new: true
}
));
If your input can have missing fields, you can build a dynamic query in $set with only the fields you have specified in your input :
async function save(id, query) {
const user = (await User.findByIdAndUpdate(
id, {
$set: query
}, {
new: true
}
));
console.log(user);
}
var id = mongoose.Types.ObjectId("59d91f1a06ecf429c8aae221");
var input = {
newsletter: false,
blog: false
};
var query = {};
for (var key in input) {
query["subscriptions." + key] = input[key];
}
save(id, query);
I ended up doing the following:
const user = await User.findById(args.id);
// merge subscriptions
user.subscriptions = Object.assign({}, user.subscriptions, args.payload);
return user.save();
Related
This question already has answers here:
mongodb/mongoose findMany - find all documents with IDs listed in array
(9 answers)
Closed 3 months ago.
I am trying to search using node.js, ejs and mongoose. All the filter parameters are working perfectly but only categoryIds is not (stored as a collection of ObjectIDs in the mongodb document, referring to the respective document in categories collection), always giving me the empty record set.
For example:
If I need to find the a movie called Cosmos (see the attached screenshot) then I can easily find it with all or any filter except categories. Once I select any category, the record-set will go blank even if the I have selected the one which it belongs to.
model.js
const Model = mongoose.model('Movie', new Schema({
...
categoryIds: [{
type: Schema.Types.ObjectId,
trim: true,
default: null,
ref: 'Category',
}],
copyrightId: {
type: Schema.Types.ObjectId,
trim: true,
default: null,
ref: 'Copyright',
},
...
}, {
timestamps: true
});
Controller.js
Router.get('/', (req, res) => {
const search = req.query;
const conditions = (() => {
let object = {};
['releaseYear', 'languageId', 'copyrightId'].forEach(filter => {
if (search[filter] != '') {
object[filter] = search[filter];
}
});
if (typeof search.categoryIds !== 'undefined') {
object.categoryIds = [];
search.categoryIds.forEach(item => object.categoryIds.push(item));
}
if (search.keywords != '') {
object.title = {
$regex: search.keywords,
$options: 'i'
};
}
return object;
})();
const count = await Model.count(conditions);
const items = await Model.find(conditions, {
__v: false,
imdb: false,
trailer: false,
createdAt: false,
updatedAt: false,
}).sort({
status: -1,
releaseYear: -1,
title: 1
})
.populate('languageId', ['title'])
.populate('copyrightId', ['title'])
.populate('categoryIds', ['title'])
.skip(serialNumber)
.limit(perPage);
...
});
All the fields in the search form
{
categoryIds: [
'6332a8a2a336e8dd78e3fe30',
'6332a899a336e8dd78e3fe2e',
'6332a87ba336e8dd78e3fe2c',
'634574ab339b1a6b09c1e144'
],
languageId: '',
copyrightId: '',
releaseYear: '',
rating: '',
seen: '',
status: '',
keywords: '',
submit: 'search' // button
}
filtered search parameters
{
categoryIds: [
'6332a8a2a336e8dd78e3fe30',
'6332a899a336e8dd78e3fe2e',
'6332a87ba336e8dd78e3fe2c',
'634574ab339b1a6b09c1e144'
]
}
Here is the screenshot of mongodb document.
...
if (typeof search.categoryIds !== 'undefined') {
object.categoryIds = {
$in: []
};
search.categoryIds.forEach(item => object.categoryIds.$in.push(
mongoose.Types.ObjectId(item))
);
}
console.log(object);
return object;
The is the final filter object
{
categoryIds: {
'$in': [
new ObjectId("6332a87ba336e8dd78e3fe2c"),
new ObjectId("634669f4a2725131e80d99f1")
]
}
}
Now, all the filters are working perfectly.
Thank you everyone.
The filter should contain all categoryIds and in the same order to match the document. It's not quite clear from the question if it is the intended functionality. If not, most popular usecases are documented at https://www.mongodb.com/docs/manual/tutorial/query-arrays/
I don't recall how mongoose handles types when you query with array function like $all, so you may need to convert string IDs to ObjectIDs manually, e.g.:
search.categoryIds.forEach(item => object.categoryIds.push(
mongoose.Types.ObjectId(item))
);
I'm having trouble with my update query on mongoose. I'm not sure why other objects get deleted after I update a specific object. the code works when I update but after that, the rest of the objects inside the array are getting deleted/removed. Literally, all of the remaining objects get deleted after the update request.
export const updateProduct = async (req,res) => {
const { id } = req.params;
try {
if(!mongoose.Types.ObjectId.isValid(id)) return res.status(404).json({ message: 'Invalid ID' });
await OwnerModels.findOneAndUpdate({'_id': id, store:{$elemMatch: {productname: req.body.store[0].productname }}},
{$set:
{
store:
{
productname: req.body.store[0].productname,
price: req.body.store[0].price,
quantity: req.body.store[0].quantity,
categoryfilter: req.body.store[0].categoryfilter,
description: req.body.store[0].description,
timestamp: req.body.store[0].timestamp
}
}
}, // list fields you like to change
{'new': true, 'safe': true, 'upsert': true});
} catch (error) {
res.status(404).json(error)
} }
I'm not sure why other objects get deleted after I update a specific object.
Because you are updating the whole object and it will replace the existing store array of object in the database,
You need to use arraFilters, and upsert is not effective in array of object updated, so i have commented,
await OwnerModels.findOneAndUpdate(
{
'_id': id,
store:{
$elemMatch: {
productname: req.body.store[0].productname
}
}
},
{
$set: {
store: {
"store.$[s].productname": req.body.store[0].productname,
"store.$[s].price": req.body.store[0].price,
"store.$[s].quantity": req.body.store[0].quantity,
"store.$[s].categoryfilter": req.body.store[0].categoryfilter,
"store.$[s].description": req.body.store[0].description,
"store.$[s].timestamp": req.body.store[0].timestamp
}
}
},
{
'arrayFilters': [
{ "s.productname": req.body.store[0].productname }
],
'new': true,
'safe': true,
// 'upsert': true
}
);
I am trying to remove one object from an array of my collection, which looks like this. It s a collection in Mongodb
Before deleting a specific object based on chartId, I need to check the userId and the name of the array. Then I need to delete the object.
I have written this code, but its not working. someone will tell me what exactly I am missing in this code.
delChartObj.updateOne(
{ 'userId': userId },
{ $pull: { "Color": { "chartId": req_chart_id } } },
{ safe: true, multi: true}, function (err, obj) {
if (err) { res.send.err }
res.status(200).send({ msg: "Deleted Sucessfully" });
});
In my case, userId = ADAM, array = "Color" and chartID = time
I am using mongoose for performing action
delChartObj is an object of model
const UserSchema = mongoose.Schema({
userId: { type: String, required: true, unique: true },
charts: { type: Object },
});
You should do findOneAndUpdate, the syntax will be something like:
Model.findOneAndUpdate(
< condition>,
{ $pull: { "Color.$.chartId": req_chart_id } } }, // The actual Query
{ new: true }
)
try this in pull
{ $pull: { "Chart.Color.$.chartId": req_chart_id } } },
why save function works with (user) even though user does not have this function
and when I print user it doesn't have any save function
I did not use findByIdAndUpdate because I wanna use pre before save or update user
I searched on google but didn't find a solution
index.js
const User = require('../models/user')
user = await User.findById(req.params.id)
user['password']='xxxxx'
await user.save()
User File
const mongoose = require('mongoose')
const validator = require('validator')
const bcrypt=require('bcryptjs')
const userSchema=mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Email is invalid')
}
}
},
password: {
type: String,
required: true,
minlength: 7,
trim: true,
validate(value) {
if (value.toLowerCase().includes('password')) {
throw new Error('Password cannot contain "password"')
}
}
},
age: {
type: Number,
default: 0,
validate(value) {
if (value < 0) {
throw new Error('Age must be a postive number')
}
}
}
})
userSchema.pre('save', async function (next) {
const user = this
if (user.isModified('password')) {
user.password = await bcrypt.hash(user.password, 8)
}
next()
})
const User = mongoose.model('User',userSchema )
module.exports = User
console.log(user) output
{
age: 20,
_id: 5f738c48bbf1cc3b2647a35b,
name: 'momo',
email: 'momomo#gmail.com',
password: 'sj,sksaklas,ans',
__v: 0
}
console.log(user['save']) output
[Function (anonymous)]
The User value is returned by the function call mongoose.model('User',userSchema )
The save() function is defined here: https://github.com/Automattic/mongoose/blob/master/lib/model.js#L424-L505
When you pass an object to console.log it typically displays only the objects own properties, not inherited ones. i.e. save is not displayed when logging a mongoose model for the same reason that console.log doesnn't display match, indexOf, ltrim, replace, etc. when logging a string.
If you really want to see the inherited properties, this might be a starting point for you:
How to console.log all inherited properties?
I have looked everywhere and couldn't find any clear answers for this.
I have a complex findAll() with many inclusions and each with their own virtual fields.
What I want is to modify the virtual fields of the result, however as it is returning the model instance trying to access the virtual fields returns undefined as they are not in the result yet.
I have tried 'raw: true' but this removes all virtual fields and as my data has nested tables which also have their own virtual fields which I need, I cannot do that.
Example models
var Book = sequelize.define('Book', {
id: {
type: DataTypes.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
title: {
type: DataTypes.STRING
},
author: {
type: DataTypes.STRING
}
//....other columns,
myField: {
type: DataTypes.Virtual,
get() {
return this.getDataValue('title:') + this.getDataValue('author');
})
Getting the data
model.Book.findAll({
limit: 100
})
.then((result) => {
const newBook = result.map(row => {
return {...row, myField: 'setMyOwnValueHere'}
}
return newBook
}
Get model data first : get
model.Book.findAll({
limit: 100
}).then(result => {
const books = result.map(row => {
//this returns all values of the instance,
//also invoking virtual getters
const book = row.get();
book.myField = 'setMyOwnValueHere';
return book;
});
return books;
});