Mongoose objectId未保存在另一个集合中

时间:2016-01-25 08:01:58

标签: node.js mongodb mongoose

我是mongoose和nodejs的新手。保存集合时,请帮助我了解代码中的错误。我的user.js如下所示

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');

var UserSchema = new Schema ({
name: { type: String, required: true },
username:{ type:String, required: true, index:{ unique: true}},
password:{ type: String, required: true, select: false},
email:{ type: String, required: true, select: true},
mobile:{ type: String, required: true, select: true},
nativecid:{ type: Schema.Types.ObjectId, ref:'City'},
regdate:{ type: Date, default: Date.now },
did:{ type: String, required: false }
});

UserSchema.pre('save', function(next){

var user = this;

if(!user.isModified('password')) return next();
bcrypt.hash(user.password, null, null, function(err, hash){
if(err) return next(err);
user.password = hash;
next();
});
});

UserSchema.methods.comparePassword = function(password){
var user = this;
return bcrypt.compareSync(password, user.password);
};

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

我的城市模型即city.js如下所示

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var CitySchema = new Schema({
name: { type: String, required: true },
status: { type: Boolean, default: true },
date: { type: Date, default: Date.now }
});

module.exports = mongoose.model( 'City', CitySchema );

城市已存储在数据库中,如下所示

{ "_id" : ObjectId("56a4a0adb0f445561cfd4e37"), "name" : "New York", "date" : ISODate("2016-01-24T10:00:13.220Z"), "status" : 1, "__v" : 0 }

我希望在用户注册时将纽约的ObjectId保存在用户集合中。我在尝试如下,但没有成功。

var User = require('../models/user');
var City = require('../models/city');

api.post('/signup', function(req, res){

    var user = new User({
        name: req.body.name,
        username: req.body.username,
        password: req.body.password,
        email: req.body.email,
        mobile: req.body.mobile
     });
     City
        .findOne({ name: "New York" })
        .populate('_id') 
        .exec(function (err, city1) {
        if(err){
            res.send(err);
            return;
        }
        console.log('The creator is %s', city1.name);
      return user.nativecid = city1._id;

    })   

    user.save(function(err){
        if(err){
            res.send(err);
            return;
        }

        res.json({
            success: true,
            message: 'User created successfully!'
        });
    });
});

我不明白出了什么问题。请指教我。

1 个答案:

答案 0 :(得分:0)

只需将用户保存在 city.findOne (嵌套)中,并且可能无需填充您应该使用投影

City.findOne({ name: "New York" }, {name:1}) // ID return defaulat
        .exec(function (err, city1) {
        if(err){
            res.send(err);
            return;
        }
        console.log('The creator is %s', city1.name);
        user.nativecid = city1._id;

        user.save(function(err1){
            if(err1){
                res.send(err1);
                return;
            }

            res.json({
                success: true,
                message: 'User created successfully!'
            });
        });

    })