我是NodeJS和MongoDB的新手,在创建示例应用时遇到了以下问题
// ************ this is testusers.js file ************//
var userdetails = require('userdetails');
var mongoose = require('mongoose');
var schema = mongoose.Schema;
var geekDetails = new schema({
description: String,
details: {
type: mongoose.Schema.Types.ObjectId,
ref: 'userDetails'
}
});
module.exports = {
model: mongoose.model('geekDetails',geekDetails),
schema: geekDetails
};
// ************ this is user.js file ************//
var mongoose = require('mongoose');
var schema = mongoose.Schema;
var userDetails = new schema({
firstName: String,
lastName: String,
email: String,
password: String
});
module.exports = {
model: mongoose.model('userDetails',userDetails),
schema: userDetails
};
// ************ this is create.js file [used to save the details to DB] *******//
var testusers = require('testusers.js');
var mongoose = require('mongoose');
adduser = function(firstName,lastName,email,password,passwordConfirmation,description,callback){
new testusers.model({
description: description,
details: {
firstName: firstName,
lastName: lastName,
email: email,
password: password
}
}).save(function(err,result){
if (err){
callback(err,null);
}
else {
callback(null,result);
}
});
当我尝试保存详细信息时,它返回了以下错误“强制转换为objectid,路径'详细信息'中的值对象对象失败了”我确信我在使用模式做错了但我不能弄明白了。
提前致谢
答案 0 :(得分:2)
像这样保存参考文档不会以这种方式使用mongoose。这是另一种选择。实际上,您需要先保存嵌入的文档(userdetails
)并使用id保存父级(testuser
)。
adduser= function(firstName,lastName,email,password,passwordConfirmation,
description,callback){
new userDetails.model({
firstName:firstName,
lastName:lastName,
email:email,
password:password
}).save(function(err,doc){
new testusers.model({
description:description,
details: doc._id
}).save(function(err,result){
if(err){callback(err,null);}
else{callback(null,result);}
});
});
}
使用promises可以使这段代码更好阅读,但这应该可以提供这个想法。