Failed to update single property by mongoose - node.js

Frist I have read and try the solution in the post of mongoose-and-partial-select-update.
However when I try to use the traditional style, query would work.
My schema:
var userSchema = mongoose.Schema({
local: {
email: {
type: String,
index: {
unique: true,
dropDups: true
}
},
password: String,
displayName: String,
avatar: {
type: String,
default: "./img/user.png"
},
role: {
type: String,
default: "student"
},
ask_history: [
{
question_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'questionAnswer'
},
favorite: Boolean,
ask_time: Date
}
],
interest: [String]
}
})
Working Update function:
User.findById(id, function(err, User) {
if (err) {
throw done(err);
}
if (!User) {
return;
}
User.local.role = "admin";
User.save(function(err, updatedUser) {
if (err) {
throw err
} else {
//good
}
})
});
However if I do this:
User.update({_id : id},
{$set{
local:{role:"admin"}
}
},function(...){...}
});
Code above will overwrite user into:
{
_id : "...",
local: {
role : "admin"
}
}
I read that $ will make the update only changing property, where I did wrong?

The positional operator $ works with array of subdocuments.
In your case you have a single sub-document, so the following should work:
User.update({_id : id},
{ $set
{
"local.role": "admin"
}
}, function(...){...}
});

Related

Mongoose: populate an object inside an array

I have a schema exported like that:
const PackageSchema = new Schema({
name: { type: String, required: true },
maneuver: [
{
maneuverId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: ManeuverMainly,
},
period: { type: String, enum: ["day", "night"], required: true },
},
],
timestamp: { type: Date, default: Date.now() },
});
When I make a find() like that:
Package.find().populate("maneuver", "name").exec((err, data) => {
if (err) {
res.status(500).send({ message: "Failed!" });
return;
}
res.status(200).send(data);
});
My populate method does not work. How can I populate my every maneuverId from PackageSchema with my name column from ManeuverMainlySchema?
Obs: my ManeuverMainlySchema bellow:
const ManeuverMainlySchema = new Schema({
name: { type: String, required: true },
description: { type: String, required: true },
timestamp: { type: Date, default: Date().now },
});
taken from Mongoose populate with array of objects containing ref you have to specify the field within the object of the array you want to populate against.
Package.find().populate("maneuver.maneuverId", "name").exec((err, data) => {
if (err) {
res.status(500).send({ message: "Failed!" });
return;
}
res.status(200).send(data);
});
Package.find().populate(["maneuver.maneuverId", "name"]).exec((err, data) => {
if (err) {
res.status(500).send({ message: "Failed!" });
return;
}
res.status(200).send(data);
});
If you want to populate one of them, don't need to use array in populate as
populate("maneuver.maneuverId") or populate("name").

I want to pass array object inside array subdocument in mongoose

Here is my Schema
I am trying to add replies array inside answers array. If someone answers a question and if someone wants to reply on the given answer
const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema;
const questionSchema = new mongoose.Schema(
{
postedBy: {
type: ObjectId,
required: true,
ref: "User",
},
question: {
type: String,
required: true,
},
photo: {
data: String,
required: false,
},
answers: [
{
userId: { type: ObjectId, ref: "User" },
answerType: {
data: String,
required: false,
},
answer: String,
replies: [
{
userId: { type: ObjectId, ref: "User" },
reply: String,
replyType: {
data: String,
required: false,
},
},
],
},
],
questionType: {
data: String,
required: false,
},
createdAt: {
type: Date,
required: true,
default: Date.now,
},
},
{ timeStamps: true }
);
module.exports = mongoose.model("Question", questionSchema);
Here is my Controller method
exports.postReply = (req, res) => {
const reply = req.body.reply || "";
const userId = req.user._id || "";
const answerId = req.body.answerId || "";
Question.findByIdAndUpdate(
{ _id: answerId },
({ $push: { answers: { answer: { replies: { reply, userId } } } } },
{ new: true }),
(err, newReply) => {
if (err) {
res.status(400).json({
error: errorHandler(err),
});
} else {
res.json({
msg: "Reply posted successfully",
newReply,
});
}
}
);
};
I feel I am going wrong on the findOneAndUpdate method. I am getting no error on the console but newReply comes null. Any help will be appreciated.
I would suggest you using the $addToSet instead of the $push operator as you are adding a document to the array. (see: https://docs.mongodb.com/manual/reference/operator/update/addToSet/).
If you want to add more than one document to the array, refer also to the $each operator together with $addToSet.
So your coding can look similiar to this (note: the variable 'yourDocument' is the document you want to add):
Question.findByIdAndUpdate(
{ _id: answerId },
{ $addToSet: { answers: yourDocument } },
{ new: true },
(err, newReply) => {
if (err) {
res.status(400).json({
error: errorHandler(err),
});
} else {
res.json({
msg: "Reply posted successfully",
newReply,
});
}
}
);
};
The problem is clearly the parentesis around
({ $push: { answers: { answer: { replies: { reply, userId } } } } }, { new: true })
Doing this console.log( ({a:1}, {b:2}) ); will log {b: 2} which means you are doing this
Question.findByIdAndUpdate( { _id: answerId }, { new: true }, (err, newReply) => {
So remove the parentesis and you should be good
Question.findByIdAndUpdate(
{ _id: answerId },
{ $push: { answers: { answer: { replies: { reply, userId } } } } },
{ new: true },
(err, newReply) => {
if (err) {
res.status(400).json({
error: errorHandler(err),
});
} else {
res.json({
msg: "Reply posted successfully",
newReply,
});
}
}
);

Cast to ObjectId failed for value at path for model error

This is my Profile Schema:
const mongoose = require('mongoose');
const ProfileSchema = new mongoose.Schema({
user: {
// Special field type because
// it will be associated to different user
type: mongoose.Schema.Types.ObjectId,
ref: 'user',
},
company: {
type: String,
},
website: {
type: String,
},
location: {
type: String,
},
status: {
type: String,
required: true,
},
skills: {
type: [String],
required: true,
},
bio: {
type: String,
},
githubusername: {
type: String,
},
experience: [
{
title: {
type: String,
required: true,
},
company: {
type: String,
required: true,
},
location: {
type: String,
},
from: {
type: Date,
required: true,
},
to: {
type: Date,
},
current: {
type: Boolean,
default: false,
},
description: {
type: String,
},
},
],
education: [
{
school: {
type: String,
required: true,
},
degree: {
type: String,
required: true,
},
fieldofstudy: {
type: String,
required: true,
},
from: {
type: Date,
required: true,
},
to: {
type: Date,
},
current: {
type: Boolean,
default: false,
},
description: {
type: String,
},
},
],
social: {
youtube: {
type: String,
},
twitter: {
type: String,
},
facebook: {
type: String,
},
linkedin: {
type: String,
},
instagram: {
type: String,
},
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = Profile = mongoose.model('profile', ProfileSchema);
This is my view api. It doesn't work. it only return Cast to ObjectId failed for value { 'experience._id': '5edcb6933c0bb75b3c90a263' } at path _id for model profile
router.get('/experience/viewing/:viewexp_id', auth, async (req, res) => {
try {
const exp = await Profile.findById({
'experience._id': req.params.viewexp_id,
});
if (!exp) {
return res.status(404).json({ msg: 'Experience not found' });
}
res.json(exp);
} catch (err) {
console.error(err.message);
res.status(500).send(err.message);
}
});
How can I fix this? I tried looking at the stackoverflow of the same errors. still it doesn't seem to work.
and this is what I am trying to hit
The problem is that you have to convert your string _id to mongoose object id using this function mongoose.Types.ObjectId and my suggestion is to use findOne function instead of findById,
var mongoose = require('mongoose');
router.get('/experience/viewing/:viewexp_id', auth, async (req, res) => {
try {
let id = mongoose.Types.ObjectId(req.params.viewexp_id);
const exp = await Profile.findOne(
{ "experience._id": req.params.viewexp_id },
// This will show your sub record only and exclude parent _id
{ "experience.$": 1, "_id": 0 }
);
if (!exp) {
return res.status(404).json({ msg: 'Experience not found' });
}
res.json(exp);
} catch (err) {
console.error(err.message);
res.status(500).send(err.message);
}
});
var mongoose = require('mongoose');
router.get('/experience/viewing/:viewexp_id', auth, async (req, res) => {
try {
const exp = await Profile.findOne({
'experience._id': mongoose.Types.ObjectId(req.params.viewexp_id),
});
if (!exp) {
return res.status(404).json({ msg: 'Experience not found' });
}
res.json(exp);
} catch (err) {
console.error(err.message);
res.status(500).send(err.message);
}
});
You are saving object id . but your param id is string. convert it in ObjectId. Please check my solution.
router.post(
"/",
[
auth,
[
check("status", "status is required").not().isEmpty(),
check("skills", "skills is required").not().isEmpty(),
],
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const {
company,
website,
location,
bio,
status,
githubuername,
skills,
youtube,
facebook,
twitter,
instagram,
linkedin,
} = req.body;
const profileFileds = {};
profileFileds.user = req.user.id;
if (company) profileFileds.company = company;
if (website) profileFileds.website = website;
if (location) profileFileds.location = location;
if (bio) profileFileds.bio = bio;
if (status) profileFileds.status = status;
if (githubuername) profileFileds.githubuername = githubuername;
if (skills) {
profileFileds.skills = skills.split(",").map((skill) => skill.trim());
}
//Build profile object
profileFileds.social = {};
if (youtube) profileFileds.social.youtube = youtube;
if (twitter) profileFileds.social.twitter = twitter;
if (facebook) profileFileds.social.facebook = facebook;
if (linkedin) profileFileds.social.linkedin = linkedin;
if (instagram) profileFileds.social.instagram = instagram;
try {
let profile = await Profile.findOne({ user: req.user.id });
if (profile) {
//update
profile = await Profile.findOneAndUpdate(
{ user: req.user.id },
{ $set: profileFileds },
{ new: true }
);
return res.json(profile);
}
//Create profile
profile = new Profile(profileFileds);
await profile.save();
res.json(profile);
} catch (err) {
console.error(err.message);
res.status(500).send("server Error");
}
}
);

Error:Can't canonicalize query: BadValue Unsupported projection option

User Schema
var UserSchema = new Schema({
name: String,
username: { type: String, required: true, index: { unique: true }},
password: { type: String, required: true, select: false},
favouriteid:[{eventid:String}]
});
Event Schema
var EventSchema=new Schema({
name:String,
location:{ type:String },
description:{type:String },
price: String,
rating: {
value: String,
count: {type: String, default: 10},
userrating: [{
uservalue: String,
userid: String
}]
},
imageurl:[String],
userimageurl:[String],
reviews:[{ userid:String,
username: String,
comment:String}]
});
POST METHOD to push the value of userid and uservalue in Event Schema.
api.post('/rateevent', function (req, res) {
var userid = req.body.userid;
var uservalue = req.body.uservalue;
var eventid = req.body.eventid;
Event.findById({_id: eventid},
{$push: {rating: {userrating: {uservalue: uservalue, userid: userid}}}},
{upsert: true},
function (err, events) {
if (err) {
res.send(err);
return;
}
else {
calculaterating(events);
}
});
function calculaterating(event) {
event.rating.count++;
event.rating.value = (event.rating.value * (event.rating.count - 1) + uservalue) / event.rating.count;
res.json("rating updated");
}
});
It is showing the following error:
{
"name": "MongoError",
"message": "Can't canonicalize query: BadValue Unsupported projection option: $push: { rating: { userrating: { uservalue: \"5\", userid: \"56593f3657e27af8245735d7\" } } }",
"$err": "Can't canonicalize query: BadValue Unsupported projection option: $push: { rating: { userrating: { uservalue: \"5\", userid: \"56593f3657e27af8245735d7\" } } }",
"code": 17287
}
Is the post method not correct? I have seen other mongodb documents but not able to find this type of thing. I am new to node js. Help me.
It should be Event.update instead of Event.findById, Also your push operation looks wrong. It should be like this:
Event.findOneAndUpdate(
{_id: eventid},
{$push: {'rating.userrating': {uservalue: uservalue, userid: userid}}},
{new: true},
function (err, events) {
if (err) {
res.send(err);
return;
}
else {
if(events.length > 0){
calculaterating(events);
}
else {
res.json({msg: "Nothing to update"});
}
}
});
function calculaterating(event) {
event = event[0]; //get the object from array
event.rating.count++;
event.rating.value = (event.rating.value * (event.rating.count - 1) + uservalue) / event.rating.count;
Event.update(
{_id: eventid},
{$set: {
'rating.count': event.rating.count,
'rating.value': event.rating.value
}},
function(err, response){
if (err) {
res.send(err);
return;
}
else {
res.json({msg: "rating updated"});
}
});
}
In events variable you will get the document that was updated in the new state. If you had passed {new: false} you will get the document as it was before the update.
in MY case
i was using the wrong method like below i was updating the record by
findOne , that can`t be possible , in my case , thats why issues
occurs
Solution: if you want to update the record , use .update() method,
and if you want to find records , then you can use .find() , .findOne() , don`t mismatch
domain.Cart.findOne({
UserId: req.body.UserId,
shopId: req.body.shopId,
},
{ $addToSet: { "productDetails": _productDetails } }
).exec(function (err, results) {
console.log(err, results)
callback(null, {
result: results,
msg: "productCount has been updated"
})
})

Issues With Mongoose $push

I really just need a second set of eyes here. I am using the Mongoose npm to create a new entry in my MongoDB. Then I am using that new entry in a few functions in the Async npm.
The issue that I am having is that I am getting the first three console logs, "hitter", "create", and "req.body.campaign_id" but nothing past that. I think it has to do with my $push in the first findByIdAndUpdate. Please see my code and schema below.
Code! See async parallel "campaign" function
Bid.create(req.body, function(err, bid){
console.log('create')
async.parallel({
campaign: function(done) {
console.log(req.body.campaign_id)
Camapaign.findByIdAndUpdate(req.body.campaign_id, {
$push: { bids: bid._id }
}, {
safe: true,
upsert: true
}, function(err, campaign){
console.log('camp', 2)
if(err) {
console.log(err)
done(err)
} else {
done(null, campaign)
}
});
},
user: function(done) {
console.log('user', 1)
User.findByIdAndUpdate(req.body.user_id, {
$push: {'bids': bid._id }
}, {
safe: true,
upsert: true
}, function(err, bid){
console.log('user', 2)
if(err) {
done(err)
} else {
done(null, bid)
}
});
}
}, function(err, response){
console.log('response')
if(err) {
console.log(err)
} else {
res.status(200).send(response);
}
});
})
Campaign Schema
var campaignSchema = new mongoose.Schema({
title:String,
imgUrl:[String],
shortDesc: { type: String, set: shortenDesc },
longDesc:String,
duration: Number,
price: Number,
desired_price: Number,
bids: [{ type: mongoose.Schema.Types.ObjectId, ref: 'bidSchema' }],
owner_id: { type: mongoose.Schema.Types.ObjectId, ref: 'userSchema' }
});
User Schema
var schema = new mongoose.Schema({
name: String,
email: {
type: String
},
password: {
type: String
},
salt: {
type: String
},
twitter: {
id: String,
username: String,
token: String,
tokenSecret: String
},
facebook: {
id: String
},
google: {
id: String
},
campaigns: [campaignSchema],
bids: [{type: mongoose.Schema.Types.ObjectId, ref: 'bidSchema'}]
});
Please let me know if you need to see anything else. All help is appreciated.
Thanks!
You are doing Camapaign.findByIdAndUpdate are you sure Camapaign isn't mispelled there? Shouldn't it be Campaign?

Resources