gpt4 book ai didi

node.js - 类型错误 : Cannot use 'in' operator to search for '_id' in male

转载 作者:IT老高 更新时间:2023-10-28 13:14:54 24 4
gpt4 key购买 nike

您好,我在使用新版本的 node.js 时遇到问题之前我用过这样的代码

 label(for='user_sex') Sex:
select(id='user_sex', name='user[sex]')
option(id='user_male',value=user.sex,selected=1)='male'
option(id='user_female',value=user.sex)='female'

以及 app.js 中的代码

 var user = new User(req.body.user);
-- other code
var sex = new User(req.body.user.sex);
User.find({}, function(err, users) {
for(var i = 0;i< users.length;i++) {
if(users[i].email == email) {
useremail = users[i].email;
}
}
if(!useremail) {
user.save(function(err) {
if (err) return userSaveFailed();
req.flash('info', 'Your account has been created');
emails.sendWelcome(user);

switch (req.params.format) {
case 'json':
res.send(user.toObject());
break;

default:
req.session.user_id = user.id;
res.redirect('/userinfo');
}
});
}

完整的错误日志如下:

500 TypeError: Cannot use 'in' operator to search for '_id' in male

at model.Document.$__buildDoc (C:\SocialNetwork\node_modules\mongoose\lib\document.js:159:27)
at model.Document (C:\SocialNetwork\node_modules\mongoose\lib\document.js:58:20)
at model.Model (C:\SocialNetwork\node_modules\mongoose\lib\model.js:38:12)
at new model (C:\SocialNetwork\node_modules\mongoose\lib\model.js:2092:11)
at C:\SocialNetwork\app.js:1033:13
at callbacks (C:\SocialNetwork\node_modules\express\lib\router\index.js:272:11)
at param (C:\SocialNetwork\node_modules\express\lib\router\index.js:246:11)
at param (C:\SocialNetwork\node_modules\express\lib\router\index.js:243:11)
at pass (C:\SocialNetwork\node_modules\express\lib\router\index.js:253:5)
at Router._dispatch (C:\SocialNetwork\node_modules\express\lib\router\index.js:280:5)

问题似乎与我知道现在已弃用的连接表单有关,所以我现在使用的是强大的。谁能帮我解决这个错误

最佳答案

您收到此错误是因为您没有正确构建模型实例。它需要属性的哈希值及其对应的值,但您提供的参数是一个字符串。从上面的代码中, req.body.user 是一个哈希 {sex: "male"} 而 req.body.user.sex 只是一个字符串 "male"。可以的;

user = new User({sex: "male"});

但你不能这样做;

user = new User("male");

这解释了为什么您的第一个带有 req.body.user 参数的“用户”实例可以工作,但带有 req.body.user.sex 参数却失败了。我还不确定你想用 var sex = new User(req.body.user.sex); 实现什么你想创建另一个用户模型实例吗?还是相关的性别模型?

关于node.js - 类型错误 : Cannot use 'in' operator to search for '_id' in male,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15985434/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com