gpt4 book ai didi

node.js - Mongoose 架构字段定义问题(关键字 : nodejs, req.body、extend、field、type)

转载 作者:太空宇宙 更新时间:2023-11-03 23:35:57 24 4
gpt4 key购买 nike

我花了半个小时才弄清楚问题所在,所以我需要发布这个问题以节省您的宝贵时间。

<小时/>

我有一个架构,其定义如下:

var mongoose = require('mongoose');
var ItemSchema = new mongoose.Schema({

title: String,
desc: String,
price: Number,

owner: { // this field would be filled with req.session.user
uid: {type: Number, index: true},
nickname: String,
contact: String
}
});

module.exports = mongoose.model('ItemSchema', ItemSchema);
<小时/>

然后,如果前端发送如下post请求:

console.log( req.body );
/*
{
title: 'apple',
desc: 'nice apple',
price: 100
}
*/
<小时/>

我的 Express 路由器代码,写为:

...
req.body.owner = req.session.user;

var newItem = new ItemSchema( req.body );

newItem.save(function(err, re) {
if (err) throw err;
res.json(re);
});
<小时/>

之后,我的 ItemSchema 添加了一条记录(文档)。但它不包含用户字段,如下所示:

> db.item.findOne();
{
_id: ObjectId('xxxxxxxxxxxxxxxxxxxxxxxx'),
title: 'apple',
desc: 'nice apple',
price: 100
}
<小时/>

太奇怪了!!!用户字段在哪里???

<小时/>

我必须强调,如果 console.log( req.body ),它确实包含用户字段。

<小时/>

首先我创建了如下解决方案:

req.body.user = {
uid: req.session.user.uid,
nickname: req.session.user.nickname,
contact: req.session.user.contact
}; // It works, but looks stupid
<小时/>

然后我使用下划线:

var newItem = new ItemSchema( _.extend(req.body, {user: req.session.user}) ); // It doesn't work, I don't know why
<小时/>

最后我发现肯定是Mongoose Schema Definition的问题,于是尝试了一下:

var ItemSchema = new mongoose.Schema({

title: String,
desc: String,
price: Number,

owner: {type: { // here is the key!!!
uid: {type: Number, index: true},
nickname: String,
contact: String
}}
});
<小时/>

从那时起,不再有问题,我可以编码:

req.body.user = req.session.user; // ok
<小时/>

但是我发现我之前的定义应该没问题,如 http://mongoosejs.com/docs/guide.html介绍:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var blogSchema = new Schema({
title: String,
author: String,
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
meta: { // here, same data structure with my user field
votes: Number,
favs: Number
}
});
<小时/>

那么问题出在哪里?

最佳答案

您可以设置 subdocument schema在 Mongoose 中

var UserSchema = new mongoose.Schema({

uid: {type: Number, index: true},
nickname: String,
contact: String
}, {_id: false})

var ItemSchema = new mongoose.Schema({

title: String,
desc: String,
price: Number,

owner: UserSchema
});

关于node.js - Mongoose 架构字段定义问题(关键字 : nodejs, req.body、extend、field、type),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32460117/

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