0

I am trying to push data to readBook array in my User collections document. As seen in code bellow and console.log return both User is retrieved from db and there is data to push, however nothing is changed after code finishing to work. No error in console is shown. Please help!

I got a mongodb Schema:

const UserSchema = new mongoose.Schema({ _id: Number, type: { type: String, required: true, default: "personal" }, email: { type: String, unique: true, required: true, trim: true }, username: { type: String, unique: true, required: true, trim: true }, name: { type: String, required: true, trim: true }, password: { type: String, required: true, }, readBook: [{ id: { type: String, }, status: { type: String }, rating : { type: String } }] }); 

And trying to push data to it using express:

router.post("/ratebook", (req,res,next) => { User.findById(1) .exec( (error, user) => { if(error) { return next(error); } else { console.log(user); console.log(req.body); User.update( { _id: 1}, { $push: {"readBook": req.body}}); } }) }) 

console.log return:

{ type: 'admin', readBook: [], _id: 1, email: ‘[email protected]', username: 'username', name: ’Name Surname', password: '$2a$10$JcuZNrjEh4KNOZ04TxIKLOy4/hcCK0It0.lAAE4zGN/qPavBFx8GS', __v: 0 } { id: '1', bookRating: '4’ } 

1 Answer 1

1

You have console.log position above the update query, check the DB after the API call if the data is updated

or use following code and check console.log.

 router.post("/ratebook", (req,res,next) => { User.findById(1) .exec( (error, user) => { if(error) { return next(error); } else { console.log(user); console.log(req.body); User.update( { _id: 1}, { $push: {"readBook": req.body}}).exec( (errorU, updatedUser) => { console.log("Update error", errorU); console.log("Updated User", updatedUser); }); } }) }) 
Sign up to request clarification or add additional context in comments.

6 Comments

Update error null Updated User { n: 1, nModified: 1, opTime: { ts: Timestamp { bsontype: 'Timestamp', low: 1, high_: 1527151320 }, t: 1 }, electionId: 7fffffff0000000000000001, ok: 1 }
But still it does not update in db, and next time I execute code it still remains with empty readBook array
Can you check what is in your req.body? using console may be?
{ id: '1', bookRating: '4’ } is req body
the keys in the re.body object should be same as your schema. say your req.body should be { id: 1, status: active, rating : 4 }
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.