node.jsmongodb一对多关联错误

node.js mongodb one-to-many association error

我在 (user 1<--->1..*robot) 之间遇到一对多关联错误,我想在新用户订阅时添加一个新文档,他应该添加一个新机器人(参考和名称),因此用户信息应作为新文档添加到用户集合中,机器人信息应作为新集合添加到我的 mongodb 数据库中的机器人集合中。

/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 on CMD after i execute :db.robots.find().pretty();

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

以及我执行 db.users.find().pretty();

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

}

我没找到为什么用户中的机器人数组是空的??

我可以插入一个用户和一个应该出现在该用户的机器人列表中的机器人吗?

我认为您在保存时没有将新创建的 robot's _id 推送到 user 文档中的 robots 数组。

试试这个:

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;
    });
  });
});