我正在开发Express
,Node
和Mongo
作为数据库的应用程序。我有一个集合users
,user
可以有多个registered-IDs
。它就像一个one-to-many
关系。我试图在用户集合中嵌入document
,如下所示:
post(function (req, res, next) {
var pid=req.body.pid;
var sid=req.body.sid;
var rfname=req.body.rfname;
var des=req.body.des;
var brand=req.body.brand;
var model=req.body.model;
var serial=req.body.serial;
var location=req.body.location;
var arr={pid: 'pid', sid: 'sid', rfname: 'rfname' ,des: 'des', brand: 'brand', model: 'model' ,serial: 'serial', location: 'location'};
mongoose.model('User').findOne({'pemail': req.session.email}, function (err, user){
if(err){
} else {
user.registeredId = arr;
user.save(function(err){
if(err){
} else {
res.render('user/register', {'success': 'dfhlaksdhfh'});
}
})
}
});
}
我的用户架构是这样的:
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
email: String,
password: String,
fname: String,
lname: String,
plang: String,
slang: String,
country: String,
state: String,
city: String,
postalcode: String,
address1: String,
address2: String,
pemail: String,
semail: String,
age: String,
gender: String,
pphone: String,
sphone: String,
q1: String,
a1: String,
q2: String,
a2: String,
cfname: String,
clname: String,
cemail: String
});
mongoose.model('User', userSchema);
指导我,我做错了什么,因为它没有在现有文档中嵌入文档。我是否需要在架构中定义它,如果是,那么如何?
答案 0 :(得分:1)
在架构定义中,字段registeredId
未定义,默认情况下通过 strict option ,Mongoose确保传递给模型构造函数的值未在我们的模式不会保存到数据库,因此它不会创建修改后的文档。
您可以在架构中明确定义字段,也可以在架构定义中将strict选项设置为false:
// set to false..
var userSchema = new Schema({..}, { strict: false });
然后实施其中一个 findAndModify()
方法,例如 findOneAndUpdate()
,通过将新对象推送到新数组字段来更新用户文档registeredId
。所以你可以重新编写你的帖子功能:
post(function (req, res, next) {
var User = mongoose.model('User'),
pid=req.body.pid,
sid=req.body.sid,
rfname=req.body.rfname,
des=req.body.des,
brand=req.body.brand,
model=req.body.model,
serial=req.body.serial,
location=req.body.location,
arr = {
'pid': pid,
'sid': sid,
'rfname': rfname,
'des': des,
'brand': brand,
'model': model,
'serial': serial,
'location': location
},
condition = { 'pemail': req.session.email },
update = {
"$push": { 'registeredId': arr }
};
User.findOneAndUpdate(
condition,
update,
function (err, doc){
if(err){}
else {
// doc contains the modified document
res.render('user/register', {'success': 'dfhlaksdhfh'});
}
}
);
});