Home > other >  Mongoose ObjectId storage array
Mongoose ObjectId storage array

Time:09-19


I have 2 models, I'm working on, the user can have many of his favorite movies, and films can be multiple users like it, I decided to make the information stored in each of the users,
I tried to store moviesLiked array of movieid but every time I save, it throws an error, CastError: projected onto the ObjectId in path failure values' 1234 "moviesLiked",
I try to retrieve the movie object, and the movie. The id into the array, but it doesn't seem to work for me, and never delete it, I might have been doing something wrong, if someone told me that I should to which direction to go forward, because I am new about the mongoose,
Resources on the basis of an Array of ObjectIds Mongoose in 3.8
User. Js
var mongoose=require('mongoose');
Var Schema=mongoose. Schema;

Var UserSchema=new Schema ({
Username: String,
MoviesLiked: [{type: Schema ObjectId, ref: 'Movie'}]
});

The module. Exports=mongoose. Model (' User 'UserSchema);

Movie. Js
var mongoose=require('mongoose');
Var Schema=mongoose. Schema;

Var MovieSchema=new Schema ({
Id: Number,
Name: String,
});

The module. Exports=mongoose. Model (' Movie 'MovieSchema);

the path of the IThe last/index. Js
The router. The route ('/API/users/: userid/: movieid '), put (function (the req, res) {
User. FindByIdAndUpdate (
The req. Params. Userid,
{' $push: {' moviesLiked ': the req. Params. Movieid}},
Function (err, user) {
The console. The log (user);
}
);
});

Update: instead of id, although there is no work,
The router. The route ('/API/users/: userid/: movieid '), put (function (the req, res) {
Movie. FindById (the req. Params. Movieid, function (err, movies) {
User. FindByIdAndUpdate (
The req. Params. Userid,
{' $push: {' moviesLiked: movies. Id}},
Function (err, user) {
The console. The log (user);
}
);
});
});









CodePudding user response:


The type of your own ID Number, but your moviesLiked array need to type the ObjectId,
Your moviesLiked array should contain and Movie model corresponds to the id list, the default _id field in
I believe that the referee can only reference _id, but if you want to use your own ID, then you can try to set up in MovieSchema _id to your own ID, and then set your moviesLiked enter your UserSchema matching:
User. Js
var mongoose=require('mongoose');
Var Schema=mongoose. Schema;

Var UserSchema=new Schema ({
Username: String,
MoviesLiked: [{type: Number, ref: 'Movie'}]
});

Movie. Js
The module. Exports=mongoose. Model (' User 'UserSchema);


var mongoose=require('mongoose');
Var Schema=mongoose. Schema;

Var MovieSchema=new Schema ({
_id: {type: Number, unique: true},
Name: String,
});

The module. Exports=mongoose. Model (' Movie 'MovieSchema);

CodePudding user response:

[align=right]
  • Related