I
I
Ivan Sushkov2017-02-20 11:30:53
MongoDB
Ivan Sushkov, 2017-02-20 11:30:53

How can I update a populated field with Mongoose?

Good afternoon! The question will be based on a fairly simple example. There are such models:

var mongoose = require('mongoose')
, Schema = mongoose.Schema

var storySchema = Schema({
title : String,
author : { type: Schema.Types.ObjectId, ref: 'Author' }
});

var authorSchema = Schema({
name : String,
age: Number
});

var Story = mongoose.model('Story', storySchema);
var Author = mongoose.model('Author', authorSchema);

That is, we have stories and authors (models are just for example). Now Create is written, which has no particular problems to execute:
var newStory = new Story({
  title: story_title,
  author: author_id
  });

  newStory.save(function(err){
  	if(err) throw err;
  	...	
  });

My question is how can I update this document?
I use the following method, but as I understand it, it is not correct due to the fact that ObjectID is expected from me:
Story.findOneAndUpdate({ id:story_id }, { title: story_title, author: author_id }, function(err, repertoire){
  if(err) throw err;
  ...

});

I tried converting the view mongoose.Types.ObjectId(author_id) , the result is that the document is not updated. Maybe that's not the point? I will be grateful for your help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
emp1re, 2017-02-20
@jamesgoodwin

findByIdAndUpdate(id, {...} (err)=>{
 if(err) return callback(err) // some error haendler
} )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question