简体   繁体   中英

How to push to an array in mongoose

I have this code:

router.post('/setsuggestions', function(req, res, next){
  if(!req.body.username || !req.body.challengessuggestions){
    return res.status(400).json({message: challengessuggestions});
  }

  var query = { username: req.body.username };
  /*User.findOneAndUpdate(query, { challengessuggestions: req.body.challengessuggestions }, callback = function(response){
    res.json(response);
  });*/
/*
  User.findOneAndUpdate(
    query,
    {$push: {"challengessuggestions": {$oid: req.body.challengessuggestions}}},
    callback = function(response) {
        res.json(response);
    }
    );*/

  User.findOneAndUpdate(
    query,
    {$push: {challengessuggestions: req.body.challengessuggestions}},
    {safe: true, upsert: true},
    function(err, model) {
         res.json(err);
    }
);


});

When I postman like this:

邮递员配置

I get the following error:

{ "name": "MongoError", "message": "exception: The field 'challengessuggestions' must be an array but is of type OID in document {_id: ObjectId('56263b910d1a2f1f0077ffae')}", "errmsg": "exception: The field 'challengessuggestions' must be an array but is of type OID in document {_id: ObjectId('56263b910d1a2f1f0077ffae')}", "code": 16837, "ok": 0 }

This is the schema definition of AppUser:

var UserSchema = new mongoose.Schema({
    username: { type: String, lowercase: true, unique: true },
    firstname: { type: String},
    lastname: { type: String},
    difficulty: { type: String},
    isstudent: { type: Boolean },
    haschildren: { type: Boolean},
    gender: { type: String },
    email: { type: String, unique: true},
    birthdate: String,
    isdoingchallenges: { type: Boolean },
    challengescompleted: [{ type: ObjectId, ref: 'Challenge' }],
    currentchallenge: { type: ObjectId, ref: 'Challenge' },
    challengessuggestions: [{ type: ObjectId, ref: 'Challenge' }],
    hash: String,
    salt: String
});

This is the schema definiton of challenge:

var Challengeschema = new mongoose.Schema({
    name: { type: String,  initial: true, required: true, index: true },
    image: { type: Array },
    difficulty: { type: String },
    studentfriendly: { type: Boolean },
    childfriendly: { type: Boolean },
    description: { type: String }
});

I'm sending this in the function that calls the api:

Object {_id: "5631423f8c5ba50300f2b4f6", difficulty: "medium", name: "Probeer 1 van onze recepten.", __v: 0, childfriendly: true…}

This gives me following error:

D:\\Stijn\\Documenten\\EVA-project-Groep-6\\Api\\node_modules\\mongoose\\lib\\schema\\obj ectid.js:134 throw new CastError('ObjectId', value, this.path); ^ Error at MongooseError.CastError (D:\\Stijn\\Documenten\\EVA-project-Groep-6\\Api\\node _modules\\mongoose\\lib\\error\\cast.js:18:16) at ObjectId.cast (D:\\Stijn\\Documenten\\EVA-project-Groep-6\\Api\\node_modules\\m ongoose\\lib\\schema\\objectid.js:134:13) at Array.MongooseArray.mixin._cast (D:\\Stijn\\Documenten\\EVA-project-Groep-6\\ Api\\node_modules\\mongoose\\lib\\types\\array.js:124:32) at Array.MongooseArray.mixin._mapCast (D:\\Stijn\\Documenten\\EVA-project-Groep -6\\Api\\node_modules\\mongoose\\lib\\types\\array.js:295:17) at Object.map (native) at Array.MongooseArray.mixin.push (D:\\Stijn\\Documenten\\EVA-project-Groep-6\\A pi\\node_modules\\mongoose\\lib\\types\\array.js:308:25) at Query. (D:\\Stijn\\Documenten\\EVA-project-Groep-6\\Api\\routes\\ind ex.js:144:44) at D:\\Stijn\\Documenten\\EVA-project-Groep-6\\Api\\node_modules\\mongoose\\node_mo dules\\kareem\\index.js:177:19 at D:\\Stijn\\Documenten\\EVA-project-Groep-6\\Api\\node_modules\\mongoose\\node_mo dules\\kareem\\index.js:109:16 at doNTCallback0 (node.js:408:9) at process._tickCallback (node.js:337:13) 29 Oct 22:05:38 - [nodemon] app crashed - waiting for file changes before starti ng...

How do I solve this?

Query the User user using findOne() first and use the first found document that's passed to the callback to save the embedded documents with:

router.post('/setsuggestions', function(req, res, next){
    if(!req.body.username || !req.body.challengessuggestions){
        return res.status(400).json({message: challengessuggestions});
    }

    var query = { username: req.body.username };

    User.findOne(query, function (err, user){       
        if (err) //throw ...
        if (user) {
            if (user.challengessuggestions && user.challengessuggestions.length) {
                user.challengessuggestions.push(req.body.challengessuggestions);
            }
            else {
                user.challengessuggestions = [req.body.challengessuggestions];
            }

            // save changes
            user.save(function (err) {
                if (!err) {
                    // done ...
                }
            });
        }
    });    
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM