I am using mongoose for mongodb queries.
My update query returns null.
What am I doing wrong?
The query is as follows:
Model.findOneAndUpdate(criteria, updatedDetails, { 'new': true})
Example -
I have a user profile which I need to update and send the updated profile back to frontend.
User.findOneAndUpdate({mobile: "9999999999999"}, { address: "test address" }, {'new': true} )
But the result comes null instead of the updated profile.
findOneAndUpdate is now desprecated
use update, here is sample code
exports.updateSomething = (req, res) => {
Model.update({
_id: req.params.id
}, {
$set: {
bla: req.body.bla
}
})
.then(data => {
return res.status(200).json({
success: true,
message: 'Updated successfully'
})
})
.catch(err => {
return res.status(200).json({
success: false,
message: err.message
})
})
}
Related
I'm using mongoose and I would like that when I get all users send me uid instead of _id.
const allUssers = (req, res, next) => {
try {
User.find({})
.select("username")
.select("email")
.select("image")
.exec((err, users) => {
if (err) {
return res.status(400).json({
ok: false,
msg: "Error listing users",
});
}
return res.status(200).json({
ok: true,
users: users,
});
});
} catch (err) {
return res.status(500).json({
ok: false,
msg: "Please contact with administrator",
});
}
};
You can update your schema to use an alias:
let User = new Schema({
_id: { type: String, alias: "uid" }
});
Or you can map your users to something different:
return res.status(200).json({
ok: true,
users: users.map(({ _id, ...user }) => ({ uid: _id, ...user }),
});
I'm trying to return the updated document from mongodb but instead I'm console logging Null, any ideas why this might be happening? It's updating the document in the database, but it doesn't seem to want to return the full document to me so I can console log it.
User.findOneAndUpdate({userEmail}, {$set: {resetPasswordToken: token, resetPasswordExpires: now}}, function (err, res){
console.log(res);
})
Use the {new: true} option.
User.findOneAndUpdate({
email: userEmail
}, {
$set: {
resetPasswordToken: token,
resetPasswordExpires: now
}
}, {
new: true
}, function(err, res) {
console.log(res);
})
I'am trying to add to date fields and some user info fields to a document, when inserting it into mongo (using db.collection.save).
Here is my code:
collection.save(
{document},
{
$set: {
"document.createdBy": "2",
"document.updatedBy": "2",
"document.created": new Date(),
"document.updated": new Date()
}
},
(err, result) => {
if (err){
res.status(500).json({ status: 'something is wrong' })
//return next(err);
}else{
res.status(200).json({ status: 'ok' })
//return next();
}
});
Mongo only inserts the document and none if the fields in the $set. Any ideas to what I'am doing wrong?
There is no argument for the $set operator in .save() query in mongodb
So instead try to append the object before the query
document.createdBy = "2",
document.updatedBy = "2",
document.created = new Date(),
document.updated = new Date()
collection.save(document, (err, result) => {
if (err){
res.status(500).json({ status: 'something is wrong' })
//return next(err);
} else {
res.status(200).json({ status: 'ok' })
//return next();
}
})
I'm working on an app using MongoDB and Express.js.
I am creating a post handler that updates a toy (found by its id) with a new proposed name for the toy (which is pushed onto a nameIds array that contains the ids of the other proposed names):
router.post('/names', (req, res) => {
const toyId = req.body.toyId;
const name = req.body.newName;
mdb.collection('names').insertOne({ name }).then(result =>
mdb.collection('toys').findAndModify({
query: { id: toyId },
update: { $push: { nameIds: result.insertedId } },
new: true
}).then(doc =>
res.send({
updatedToy: doc.value,
newName: { id: result.insertedId, name }
})
)
)
});
However, when I test this, I receive this error:
name: 'MongoError',
message: 'Either an update or remove=true must be specified',
ok: 0,
errmsg: 'Either an update or remove=true must be specified',
code: 9,
codeName: 'FailedToParse'
I'm not new to MongoDB, but this simple call is baffling me.
Thanks for any help you can provide!
That is the format for mongo shell. Using mongo driver you would call with these arguments:
.findAndModify( //query, sort, doc, options, callback
{ id: toyId }, //query
[], //sort
{ $push: { nameIds: result.insertedId } }, // doc update
{ new: true }, // options
function(err,result){ //callback
if (err) {
throw err
} else {
res.send({
updatedToy: result.value,
newName: { id: result.insertedId, name }
})
}
}
)
I want to remove an object from an array. Here is the schema I'm working with:
event: {
invitees: {
users : [{
user: {
type: String,
ref: 'User'
},
}],
}
}
The query I'm using is listed below, but it isn't working. Basically, nothing happens when I run this script.
Event.update(
{"_id": req.params.event_id},
{"$pull": {"invitees.users.user": req.params.user_id}},
{safe: true, upsert: true},
function (err, data) {
if (err) {
console.log(err);
}
return res.json({ success: true });
}
);
What am I doing wrong?
The field of the $pull operator identifies the array to pull the elements from that match its query.
So your update should look like this instead:
Event.update(
{"_id": req.params.event_id},
// { $pull: { <array field>: <query> } }
{"$pull": {"invitees.users": {"user": req.params.user_id}}},
{safe: true, upsert: true},
function (err, data) {
if (err) {
console.log(err);
}
return res.json({ success: true });
}
);