简体   繁体   中英

node.js mongodb one-to-many association error

I got a One-to-Many association error between(user 1<--->1..*robot) , I want to add a new document when a new user subscribe he should add a new robot with (reference and nom), so the user information should be add on the user collection as new document and the robot information should be add as a new collection on the robot collection in my mongodb database.

/routes/users.js :

router.post('/register', function(req, res, next) {
//tester si username exist
 var user = new models.user({
 nom_prenom: req.body.nom_prenom,
 username: req.body.username,
 password: req.body.password,
 email: req.body.email,
 sexe: req.body.sexe,
 adresse: req.body.adresse,

 admin: false
 });
 var robot = new models.robot({
 reference: req.body.reference, 
 nom: req.body.nom,
 flag: req.body.flag        
 });
 user.save(function(err, u){
 if(err) res.json(err);
 res.json(u);
   })
 robot.save(function(err, u){
 if(err) res.json(err);
 res.json(u);
  })
    });

/models/users.js :

var mongoose = require('../config/db');

var UserSchema = mongoose.Schema({

  nom_prenom: String,
  password: String,
  username: String,
  email: String,
  //username: { String, unique:true, required:true },
  //email: { String, unique:true, required:true },
  date_naissance: Date,
  adresse: String,
  sexe: String,
  equipements:[{type: mongoose.Schema.Types.ObjectId, ref: 'Equipement'}],
  robots:[{type: mongoose.Schema.Types.ObjectId, ref: 'Robot'}],

  admin: Boolean
   });

  module.exports = mongoose.model('User', UserSchema);

/models/robot :

  var mongoose = require('../config/db');

  var RobotSchema = mongoose.Schema({
  reference: String,
  nom: String,
  flag: Boolean,
  user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
   });

  module.exports = mongoose.model('Robot', RobotSchema);

/routes/robots.js:

  router.get('/', function(req, res, next){
  models.robot.aggregate([
    {
        "$group": {
            "_id": "$user_id",
            "robots": { "$push": "$$ROOT" }
        }
    }
  ]).exec(function(err, results){ 
    if (err) res.json({error: err});
    models.user.populate(results, { "path": "_id" }, function(err, result) {
        if(err) res.json({error: err});
        console.log(result);
        res.json(result);
    });
   });   
   });

the result Postman:

机械手数组为空

  The Result on CMD after i execute :db.robots.find().pretty();

 {
    "_id" : ObjectId("57b5862673c11c840b31cc55"),
    "reference" : "Rob9999",
    "nom" : "Robot 9999",
    "flag" : false,
    "__v" : 0
 }

and the result on CMD after I execute db.users.find().pretty();

{
    "_id" : ObjectId("57b5862673c11c840b31cc54"),
    "nom_prenom" : "test",
    "username" : "test",
    "password" : "test",
    "email" : "test@orange.tn",
    "sexe" : "femme",
    "adresse" : "tunis",
    "admin" : false,
    "robots" : [ ],
    "equipements" : [ ],
    "__v" : 0

}

I don't find why the array robots in user is empty??

Can I do that insert a user and a robot that should appear in the list of robots of that user?

I think you didn't push newly created robot's _id to the robots array in user document while saving it.

Try This:

router.post('/register', function(req, res, next) {
//tester si username exist
 var user = new models.user({
 nom_prenom: req.body.nom_prenom,
 username: req.body.username,
 password: req.body.password,
 email: req.body.email,
 sexe: req.body.sexe,
 adresse: req.body.adresse,

 admin: false
 });
 var robot = new models.robot({
 reference: req.body.reference, 
 nom: req.body.nom,
 flag: req.body.flag        
 });

 // dont change the header(res.json(u)) multiple times, make sure you set the  header 
 // single time only. otherwise you may get unnecessary errors.

 robot.save(function(err, u){
     if(err) res.json(err);
     //save user only after robot is successfully saved and push its id into robots array.
     user.robots.push(u._id);
     user.save(function(err, user){
         if(err) res.json(err);
         res.json(user);
         return;
    });
  });
});

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