以下是我的模特。我想将片段集合中的数据填充到我的流中。
流:
var mongoose = require("mongoose");
var mongoosePaginate = require('mongoose-paginate');
var Schema = mongoose.Schema;
// Declare schema
var streamSchema = Schema({
user_id: {
type: String,
required: true
},
public_key: {
type: String
},
private_key: {
type: String
},
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
particle: [{
type: Schema.Types.ObjectId,
ref: 'Piece'
}],
created_at: {
type: Date,
default: Date.now,
index: 1 // Note 1
},
});
streamSchema.plugin(mongoosePaginate);
// Export schema
// Model.paginate()
mongoose.model("Stream", streamSchema);
件:
var mongoose = require("mongoose");
var mongoosePaginate = require('mongoose-paginate');
// Declare schema
var pieceSchema = new mongoose.Schema({
stream_id: {
type: String,
required: true
},
particle: {
type: Object
},
order: {
type: Number,
default: 1
},
entries_number: {
type: Number,
default: 0
},
last_entry_at: {
type: Date
},
created_at: {
type: Date,
default: Date.now,
index: 1 // Note 1
},
});
pieceSchema.plugin(mongoosePaginate);
// Export schema
// Model.paginate()
mongoose.model("Piece", pieceSchema);
我的查询:
Stream
.findOne({
public_key: publicKey
})
.select("-data -weather -location")
.populate('particle', 'particle') // only return the particle
.exec(function (err, stream) {
if (err) return handleError(err);
console.log(stream);
});
结果:
{ _id: 580f69e0922112dd54a9f4e1,
user_id: '579f52bc53d9e8cc14f504da',
title: 'Dustbox 108',
description: '....',
public_key: 'HIGENfU96Hejy7y',
private_key: 'RcWrwGaGpDVHO4WQ',
alias: 'dustbox_108',
__v: 0,
created_at: 2016-10-25T14:19:12.008Z,
particle: []
}
结果我在追求:
{ _id: 580f69e0922112dd54a9f4e1,
user_id: '579f52bc53d9e8cc14f504da',
title: 'Dustbox 108',
description: '....',
public_key: 'HIGENfU96Hejy7y',
private_key: 'RcWrwGaGpDVHO4WQ',
alias: 'dustbox_108',
__v: 0,
created_at: 2016-10-25T14:19:12.008Z,
particle: [{
"timestamp" : [
1490385416748.0,
1490385457814.0
],
"PM" : [
null,
null
],
"Particles" : [
"100",
"100"
]
}]
}
有可能吗?
这是Piece模型的示例文档:
{
"_id" : ObjectId("58d57a08b2541e37c7fe5827"),
"stream_id" : "580f69e0922112dd54a9f4e1",
"particle" : {
"timestamp" : [
1490385416748.0,
1490385457814.0
],
"PM" : [
null,
null
],
"Particles" : [
"100",
"100"
]
},
"created_at" : ISODate("2017-03-24T19:56:56.735Z"),
"entries_number" : 2,
"order" : 1,
"__v" : 0,
"last_entry_at" : ISODate("2017-03-24T19:57:37.814Z")
}
有什么想法吗?
修改
最新输出:
...
particle: [ { _id: 58d57a08b2541e37c7fe5827, particle: [Object] } ],
...
仍然不是我想要的......
答案 0 :(得分:1)
因为"粒子" field是指子文档的一个字段,它本身就是一个必须在两个级别填充的Object。
.populate({
path: 'particle',
populate: { path: 'piece.particle' }
})
查看文档(跨多个级别填充):http://mongoosejs.com/docs/populate.html